POJ - 1094 Sorting It All Out
题目意思比较简单易懂,给他t个关系式(A<B的形式),确定n个连续的字母是不是有序,无法确定还是矛盾
分析:比较容易想到拓扑排序。比如A<B可以看成,A的入度为0,B的入度为1,然后这样的式子有t个,也就是说,当某一个为字母的入度为0的时候这数就要入队列,并记下这个数(目前最小的数),然后跟比他的大的入度都要-1,但是确定时哪一种情况需要小心。有序的情况比较好确定、独立,矛盾跟无法确定的情况需要注意下,是无法的确定的情况只有在矛盾的情况是不成立的
附上自己的里程悲
#define debug #include<stdio.h> #include<math.h> #include<cmath> #include<queue> #include<stack> #include<string> #include<cstring> #include<string.h> #include<algorithm> #include<iostream> #include<vector> #include<functional> #include<iomanip> #include<map> #include<set> #define f first #define s second #define pb push_back using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll>PLL; typedef pair<int,ll>Pil; const ll INF = 0x3f3f3f3f; const double inf=1e8+100; const double eps=1e-8; const ll maxn =1e3+200; const int N = 1e4+10; const ll mod=1000007; // int in[maxn],num[maxn],G[maxn][maxn]; int n,t; // int toposort() { queue<int>q; int tmp[maxn]; memcpy(tmp,in,sizeof(in)); bool flag=0; int cnt=0; for(int i=0; i<n; i++) { if(!tmp[i]) { q.push(i); } } while(!q.empty()) { if(q.size()>1) { flag=1; } int tp=q.front(); q.pop(); num[cnt++]=tp; for(int i=0; i<n; i++) { if(G[tp][i]==1&&!(--tmp[i])) { q.push(i); } } } if(cnt!=n) return 2; if(flag) return 1; return -1; } void solve() { int i,j,tt=1; while(cin>>n>>t) { if(n==0&&t==0) break; memset(G,0,sizeof(G)); memset(in,0,sizeof(in)); bool circle=0,order=0; int flag,k; for(i=0; i<t; i++) { // cout<<(int)circle<<" "<<(int)order<<" "<<flag<<endl; char a,b,eq; cin>>a>>eq>>b; if(circle||order) continue; if(G[b-'A'][a-'A']) { circle=1; // cout<<"circle"<<endl; cout<<"Inconsistency found after "<<i+1<<" relations."<<endl; continue; } if(!G[a-'A'][b-'A']) { G[a-'A'][b-'A']=1; in[b-'A']++; } flag=toposort(); if(flag==2) { circle=1; // cout<<"circle"<<endl; cout<<"Inconsistency found after "<<i+1<<" relations."<<endl; continue; } else if(flag==-1) { order=1; k=i; } } if(order) { // cout<<"order"<<endl; cout<<"Sorted sequence determined after "<<k+1<<" relations: "; for(i=0; i<n; i++) { cout<<(char)(num[i]+'A'); } cout<<"."<<endl; } else if(!circle&&flag==1) { // cout<<"no det"<<endl; cout<<"Sorted sequence cannot be determined."<<endl; } } } int main() { ios_base::sync_with_stdio(false); #ifdef debug freopen("in.txt", "r", stdin); // freopen("out.txt","w",stdout); #endif cin.tie(0); cout.tie(0); solve(); /* #ifdef debug fclose(stdin); fclose(stdout); system("out.txt"); #endif */ return 0; }