标签:style blog http color io os java ar for
4 6 A<B A<C B<C C<D B<D A<B 3 2 A<B B<A 26 1 A<Z 0 0
Sorted sequence determined after 4 relations: ABCD. Inconsistency found after 2 relations. Sorted sequence cannot be determined.
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib> 10 #include <string> 11 #include <set> 12 #include <stack> 13 #define LL long long 14 #define pii pair<int,int> 15 #define INF 0x3f3f3f3f 16 using namespace std; 17 const int maxn = 105; 18 int n,m,cnt,in[maxn],tmp[maxn],result[maxn]; 19 vector<int>g[maxn]; 20 queue<int>q; 21 void init() { 22 for(int i = 0; i < maxn; i++) { 23 in[i] = 0; 24 g[i].clear(); 25 } 26 } 27 bool Find(int x,int y) { 28 for(int i = 0; i < g[x].size(); i++) 29 if(g[x][i] == y) return false; 30 return true; 31 } 32 int topSort() { 33 while(!q.empty()) q.pop(); 34 for(int i = 0; i < n; i++) 35 if(!in[i]) q.push(i); 36 cnt = 0; 37 bool uncertain = false; 38 while(!q.empty()) { 39 int u = q.front(); 40 if(q.size() > 1) uncertain = true; 41 q.pop(); 42 result[cnt++] = u; 43 for(int i = 0; i < g[u].size(); i++) { 44 if(--in[g[u][i]] == 0) q.push(g[u][i]); 45 } 46 } 47 if(cnt < n) return 1; 48 if(uncertain) return 2; 49 return 3; 50 } 51 int main() { 52 bool ok; 53 char u,v,op; 54 int endPoint,flag; 55 while(scanf("%d %d",&n,&m),n||m) { 56 init(); 57 ok = false; 58 getchar(); 59 flag = 2; 60 for(int i = 1; i <= m; i++) { 61 scanf("%c%c%c%*c",&u,&op,&v); 62 if(ok) continue; 63 if(op == ‘<‘ && Find(v-‘A‘,u-‘A‘)) { 64 g[v-‘A‘].push_back(u-‘A‘); 65 in[u-‘A‘]++; 66 } else if(op == ‘>‘ && Find(u-‘A‘,v-‘A‘)) { 67 g[u-‘A‘].push_back(v-‘A‘); 68 in[v-‘A‘]++; 69 } 70 memcpy(tmp,in,sizeof(in)); 71 flag = topSort(); 72 if(flag != 2) { 73 endPoint = i; 74 ok = true; 75 } 76 memcpy(in,tmp,sizeof(in)); 77 } 78 if(flag == 3) { 79 printf("Sorted sequence determined after %d relations: ", endPoint); 80 for(int i = cnt-1; i >= 0; i--) 81 printf("%c",result[i]+‘A‘); 82 puts("."); 83 } else if(flag == 1) printf("Inconsistency found after %d relations.\n",endPoint); 84 else puts("Sorted sequence cannot be determined."); 85 } 86 return 0; 87 }
标签:style blog http color io os java ar for
原文地址:http://www.cnblogs.com/crackpotisback/p/3967479.html