ABC139E 题解
happy_zero · · 题解
题目传送门。
来个最简单的做法。拿个“指针”记录一下每个人都比到第几个(希望的比赛顺序)了,然后一天天模拟并枚举
但是这样会被卡到
记得特判一下无解(没配对完但队列为空)。
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;
}