#include<bits/stdc++.h>
using namespace std;
int n, m, res, sg, out[35];
bool lt[35][35];
pair <int, int> P[3333];
void clear() {
memset(lt, 0, sizeof(lt));
}
void floyd() {
for(int k=1; k<=n; k++)
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++) {
lt[i][j] |= lt[i][k] & lt[k][j];
}
}
int check(int t) {
memset(lt, 0, sizeof(lt));
for(int i=1; i<=t; i++) {
lt[P[i].first][P[i].second] = 1;
}
floyd();
// if(t == 6) {
// cout << " ";
// for(int i=1; i<=n; i++)
// cout << (char)(i^'@') << ' ';
// cout << endl;
// for(int i=1; i<=n; i++) {
// cout << (char)(i^'@') << ' ';
// for(int j=1; j<=n; j++) {
// cout << lt[i][j] << ' ';
// }
// cout << endl;
// }
// }
int chk = 1;
for(int i=1; i<=n; i++) {
if(lt[i][i]) {
chk = -1;
goto EEEE;
}
for(int j=1; j<i; j++) {
if(lt[i][j] ^ lt[j][i]) continue;
else if(lt[i][j]) {
chk = -1;
goto EEEE;
} else if(chk > 0) {
chk = 0;
}
}
}
EEEE: return chk;
}
void solve() {
res = m+1;
sg = 0;
for(int i=1; i<=m; i++) {
char x, y, z;
cin >> x >> z >> y;
P[i] = {x^'@', y^'@'};
int w = check(i);
if(w && !sg) {
res = i; sg = w;
}
}
res *= sg;
return ;
}
void print() {
if(res > 0) {
cout << "Sorted sequence determined after " << res << " relations: ";
iota(out+1, out+n+1, 1ll);
sort(out+1, out+n+1, [](int x, int y) { return lt[x][y]; });
for(int i=1; i<=n; i++) cout << (char)(out[i]^'@');
cout << ".\n";
}
else if(res < 0) {
cout << "Inconsistency found after " << -res << " relations.\n";
}
else cout << "Sorted sequence cannot be determined.\n";
}
signed main() {
ios_base :: sync_with_stdio(0);
cin.tie(0); cout.tie(0);
while(cin >> n >> m && n+m) {
clear();
solve();
print();
}
}
这份代码下面数据输出
Sorted sequence determined after 25 relations: AZYXWVUTSRQPONMLKJIHGFEDCB.
但正确的是
Sorted sequence determined after 25 relations: ABCDEFGHIJKLMNOPQRSTUVWXYZ.
数据:
26 26
A<B
B<C
C<D
D<E
E<F
F<G
G<H
H<I
I<J
J<K
K<L
L<M
M<N
N<O
O<P
P<Q
Q<R
R<S
S<T
T<U
U<V
V<W
W<X
X<Y
Y<Z
Z<A