Tips:用于解决A<B,B<C等不等式传递问题(也可以用拓扑排序解决)
#include<bits/stdc++.h>
#include <ostream>
using namespace std;
typedef long long ll;
//#define endl '\n'
typedef pair<int, int> PII;
#define debug() cout.flush()
#define for0(i, a) for (int i = 0; i < a; ++i)
#define REP(i, a, b) for (int i = a; i < b; ++i)
#define FOR(i, a, b) for (int i = a; i <= b; ++i)
#define REPC(i, a, b, c) for (ll i = a; i < b && i < c; ++i)
#define RREP(i, a, b) for (int i = a; i >= b; --i)
const ll MOD = 1e9 + 7;
const ll mod = 998244353;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6 + 5e3;
inline void init() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
int n, m, l, r, type, dist[30][30], vis[30];
inline void floyd() {
for (int i = 0; i < n; i++) {
if (dist[i][l]) dist[i][r] = 1;
if (dist[r][i]) dist[l][i] = 1;
for (int j = 0; j < n; j++) {
if (dist[i][l] && dist[r][j]) {
dist[i][j] = 1;
}
}
}
}
inline int check() {
for (int i = 0; i < n; i++) if (dist[i][i]) return 2; //冲突
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (!dist[i][j] && !dist[j][i]) return 0; //关系无法确定
}
}
return 1; //关系确定完成
}
inline char getMin() {
for (int i = 0; i < n; i++) {
if (!vis[i]) {
int cnt = 0;
for (int j = 0; j < n; j++) {
if (!vis[j] && dist[j][i]) {
cnt++;
break;
}
}
if (!cnt) {
vis[i] = 1;
return 'A' + i;
}
}
}
}
inline void solve() {
type = 0;
memset(dist, 0, sizeof(dist));
memset(vis, 0, sizeof(vis));
int res;
for (int i = 1; i <= m; i++) {
string s;
cin >> s;
l = s[0] - 'A';
r = s[2] - 'A';
if (!type) {
dist[l][r] = 1;
floyd();
type = check();
if (type) {
res = i;
}
}
}
if (!type) {
cout << "Sorted sequence cannot be determined." << endl;
} else if (type == 1) {
cout << "Sorted sequence determined after " << res << " relations: ";
for (int i = 0; i < n; i++) {
cout << getMin();
}
cout << '.' << endl;
} else {
cout << "Inconsistency found after " << res << " relations." << endl;
}
}
signed main() {
init();
while (cin >> n >> m){
if (n == 0 && m == 0) return 0;
solve();
}
return 0;
}