三种情况分别是:
1. 在某位置可以确定拓扑排序。
2. 在某位置出现了环
3. 到最后都不能确定拓扑排序(某一位置入度为0的点有多个),可以续输入执行下去。
每输入一组数据都要做一次判断
1 #include<cstdio> 2 #include<cstring> 3 #include<vector> 4 #include<queue> 5 using namespace std; 6 const int N = 105; 7 int n, m, in[N], temp[N], ans[N], t, pos, num; 8 char X, O, Y; 9 vector<int>G[N]; 10 queue<int>q; 11 12 void init(){ 13 memset(in, 0, sizeof(in)); 14 for (int i = 0; i <= n; ++i){ 15 G[i].clear(); 16 } 17 } 18 19 int topoSort(){ 20 while (!q.empty())q.pop(); 21 for (int i = 0; i<n; ++i)if (in[i] == 0){ 22 q.push(i); 23 } 24 pos = 0; 25 bool unSure = false; 26 while (!q.empty()){ 27 if (q.size()>1) unSure = true; 28 int t = q.front(); 29 q.pop(); 30 ans[pos++] = t; 31 for (int i = 0; i<G[t].size(); ++i){ 32 if (--in[G[t][i]] == 0) 33 q.push(G[t][i]); 34 } 35 } 36 if (pos<n) return 1; 37 if (unSure) return 2; 38 return 3; 39 } 40 41 int main(){ 42 int x, y, i, flag, ok, stop; 43 while (~scanf("%d%d%*c", &n, &m),n+m){ 44 init(); 45 flag = 2; 46 ok = false; 47 for (i = 1; i <= m; ++i){ 48 scanf("%c%c%c%*c", &X, &O, &Y); 49 if (ok) continue; 50 x = X - ‘A‘, y = Y - ‘A‘; 51 if (O == ‘<‘){ 52 G[y].push_back(x); 53 ++in[x]; 54 } 55 else if (O == ‘>‘){ 56 G[x].push_back(y); 57 ++in[y]; 58 } 59 memcpy(temp, in, sizeof(in)); 60 flag = topoSort(); 61 memcpy(in, temp, sizeof(temp)); 62 if (flag != 2){ 63 stop = i; 64 ok = true; 65 } 66 } 67 if (flag == 3){ 68 printf("Sorted sequence determined after %d relations: ", stop); 69 for (int i = pos - 1; i >= 0; --i) 70 printf("%c", ans[i] + ‘A‘); 71 printf(".\n"); 72 } 73 else if (flag == 1){ 74 printf("Inconsistency found after %d relations.\n", stop); 75 } 76 else{ 77 printf("Sorted sequence cannot be determined.\n"); 78 } 79 } 80 return 0; 81 }
代码君
时间: 2024-11-07 12:20:19