容易想到拓扑排序。
然后做完了,记一个 flag
表示是否有同时入队的情况。
#include <bits/stdc++.h>
using namespace std;
const int N = 30, M = 615;
int n, m, h[N], e[M], ne[M], idx = 0;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int d[N], in[N], ans[N];
int topsort() {
for (int i = 1; i <= n; i++) in[i] = d[i];
queue<int> q;
bool flag = 1;
int cnt = 0, tot = 0;
for (int i = 1; i <= n; i++)
if (!in[i]) q.push(i), cnt++;
flag &= (cnt == 1);
while (q.size()) {
int u = q.front(); q.pop();
ans[++tot] = u;
cnt = 0;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
--in[v];
if (!in[v]) cnt++, q.push(v);
}
flag &= (cnt <= 1);
}
if (tot != n) return -1; // 有环
if (flag == 1) return 1; // 可以唯一确定
return 0;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) h[i] = -1;
for (int i = 1; i <= m; i++) {
char ch[5];
scanf("\n %s", ch + 1);
int x = ch[1] - 'A' + 1, y = ch[3] - 'A' + 1;
add(x, y), d[y]++;
int result = topsort();
if (result == -1) return printf("Inconsistency found after %d relations.\n", i), 0;
if (result == 1) {
printf("Sorted sequence determined after %d relations: ", i);
for (int j = 1; j <= n; j++) putchar(ans[j] + 'A' - 1);
putchar('.'), putchar('\n');
return 0;
}
}
puts("Sorted sequence cannot be determined.");
return 0;
}