POJ 1094
#include<iostream> #include<stdio.h> #include<algorithm> #define MAXN 30 using namespace std; char upper[MAXN]; bool rel[MAXN][MAXN]; int n; void update(); int count(); void sort_upper(); int main() { //freopen("acm.acm","r",stdin); int m; char c_1; char c_2; char op; int i; int j; bool inco; bool sort; int time; int sort_num; while(cin>>n>>m) { if(!n && ! m) break; memset(rel,false,sizeof(rel) ); for(char a = 'A'; a <= 'Z'; ++ a) { upper[a-'A'] = a; } inco = false; sort = false; for(i = 0; i < m; ++ i) { cin>>c_1>>op>>c_2; if(inco || sort) continue; rel[c_1 - 'A'][c_2 - 'A'] = true; if(rel[c_2 - 'A'][c_1 - 'A'] == true) { inco = true; time = i+1; continue; } update(); sort_num = count(); // cout<<sort_num<<endl; // cout<<i<<endl; if(sort_num == n * (n - 1) / 2 ) { sort = true; time = i+1; continue; } } if(inco) { cout<<"Inconsistency found after "<<time<<" relations."<<endl; } else if(sort) { sort_upper(); cout<<"Sorted sequence determined after "<<time<<" relations: "; for(i = 0; i < n; ++ i) { cout<<upper[i]; } cout<<"."<<endl; } else { cout<<"Sorted sequence cannot be determined."<<endl; } } } void update() { int i; int j; int k; for(k = 0; k < n; ++ k) { for(i = 0; i < n; ++ i) { for(j = 0; j < n; ++ j) { if(rel[i][k] && rel[k][j]) rel[i][j] = true; } } } } int count() { int ans = 0; int i; int j; for(i = 0; i < n; ++ i) { for(j = 0; j < n; ++ j) { if(rel[i][j]) ++ ans; } } return ans; } void sort_upper() { int i; int j; for(i = 0; i < n; ++ i) { for(j = i + 1; j < n; ++ j) { if(rel[upper[j] - 'A'][upper[i] - 'A']) { iter_swap(&upper[i],&upper[j]); } } } }
关注我的公众号,当然,如果你对Java, Scala, Python等技术经验,以及编程日记,感兴趣的话。
技术网站地址: vmfor.com