ABC139E 题解

· · 题解

题目传送门。

来个最简单的做法。拿个“指针”记录一下每个人都比到第几个(希望的比赛顺序)了,然后一天天模拟并枚举 i,若当前 i 希望和 j 比,j 也希望和 i 比那么他俩就一定能比,对数加一,直到对数等于总轮数就跳出循环。

但是这样会被卡到 O(n^3),考虑优化。由于只有前一轮“指针”被更新这一轮才会产生新的答案,不然之前早贡献了,所以可以拿个队列记录下上一轮哪几个被更新了,这次才遍历,因为这样 a 数组的一个位置只会进队一次,所以时间复杂度是 O(n^2)。

记得特判一下无解(没配对完但队列为空)。

Code

#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
inline int read() {
    int w = 1, q = 0;
    char ch = ' ';
    while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
    if (ch == '-')
        w = -1, ch = getchar();
    while (ch >= '0' && ch <= '9') q = q * 10 + ch - '0', ch = getchar();
    return w * q;
}
int n, a[N][N], st[N], e[N][N];
//st[i] 表示第 i 个人当前需要配对的位置
//e[i][j] = 1 则说明 i 想要和 j 配对,反之亦然
int head = 1, tail, q[N * N * 2];
//这里要遍历队列所以我手写队列了
int main() {
    n = read();
    for (int i = 1; i <= n; i++)
        for (int j = 1; j < n; j++)
            a[i][j] = read();
    for (int i = 1; i <= n; i++)
        st[i] = 1, q[++tail] = i;//第一轮所有人都可以被更新
    int cnt = 0, day = 0;//cnt 表示配对数(比赛场数)
    for (; cnt * 2 < n * (n - 1) && head <= tail; day++) {
        int ttail = tail;//只更新上一轮的
        //要先把所有设为一,因为有可能正好是上一轮更新过的两两配对就错了
        for (int t = head; t <= tail; t++) {
            int i = q[t];
            int j = a[i][st[i]];
            e[i][j] = 1;
        }
        for (int t = head; t <= ttail; t++){
            int i = q[t]; head++;
            int j = a[i][st[i]];
            if (e[j][i] == 1 && e[i][j] == 1) {
                e[i][j] = e[j][i] = 0;
                cnt++;
                st[j]++, st[i]++;//指向下一个人
                if (st[i] < n) q[++tail] = i;
                if (st[j] < n) q[++tail] = j;
            }
        }
    }
    cout << (cnt * 2 == n * (n - 1) ? day : -1);//记得特判无解
    return 0;
}