传递闭包模板

本文最后更新于:3 years ago

Tips:用于解决A<B,B<C等不等式传递问题(也可以用拓扑排序解决)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#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;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!