You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.3 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 26;
int n, m;
2 years ago
bool g[N][N];
2 years ago
bool st[N];
int check() {
for (int i = 0; i < n; i++)
2 years ago
if (g[i][i]) return 2; // 矛盾
2 years ago
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
2 years ago
if (!g[i][j] && !g[j][i]) // 待继续
return 0;
2 years ago
2 years ago
return 1; // 找到顺序
2 years ago
}
2 years ago
string getorder() { // 升序输出所有变量
char s[26];
for (int i = 0; i < n; i++) {
int cnt = 0;
// f[i][j] = 1表示i可以到达j (i< j)
for (int j = 0; j < n; j++) cnt += g[i][j]; // 比i大的有多少个
// 举个栗子i=0,表示字符A
// 比如比i大的有5个共6个字符ABCDEF
// n - cnt - 1 = 6-5-1 = 0,也就是A放在第一个输出的位置上, 之所以再-1是因为下标从0开始
s[n - cnt - 1] = i + 'A';
}
// 转s字符数组为字符串
string res;
for (int i = 0; i < n; i++) res = res + s[i];
return res;
2 years ago
}
int main() {
while (cin >> n >> m, n || m) {
2 years ago
memset(g, 0, sizeof g);
2 years ago
int type = 0, t;
for (int i = 1; i <= m; i++) {
char str[5];
cin >> str;
int a = str[0] - 'A', b = str[2] - 'A';
2 years ago
// a<b,那么不需要完全的重新计算完整的传递闭包只需要把与a,b相关的变更进行记录大小关系即可
2 years ago
if (!type) {
2 years ago
g[a][b] = 1;
2 years ago
for (int x = 0; x < n; x++) {
2 years ago
if (g[x][a]) g[x][b] = 1; // 所有比a小的x,一定比b小
if (g[b][x]) g[a][x] = 1; // 所有比b大的x,一定比a大
2 years ago
for (int y = 0; y < n; y++)
2 years ago
if (g[x][a] && g[b][y])
g[x][y] = 1;
2 years ago
}
type = check();
if (type) t = i;
}
}
if (!type)
puts("Sorted sequence cannot be determined.");
else if (type == 2)
printf("Inconsistency found after %d relations.\n", t);
else {
2 years ago
string ans = getorder(); // 输出升序排列的所有变量
printf("Sorted sequence determined after %d relations: %s.\n", t, ans.c_str());
2 years ago
}
}
return 0;
}