Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 27730 | Accepted: 9602 |
Description
Input
Output
Sample Input
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
Sample Output
Sorted sequence determined after 4 relations: ABCD. Inconsistency found after 2 relations. Sorted sequence cannot be determined.
Source
East Central North America 2001
分析:拓扑排序,边输入边检查,有wa的同学点这里http://poj.org/bbs?problem_id=1094
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<queue> #include<map> #include<cmath> #define INF 0x3f3f3f3f using namespace std; const int MAXM=1005; int ecnt,first[27],in[27],_in[27],h[27],g[27][27]; int nex[MAXM],v[MAXM]; int topsort(int n) { queue<int>q; memset(h,0,sizeof h); for(int i=1;i<=n;i++) if(!in[i])q.push(i); int cur=0,maxh=0; while(!q.empty()) { int x=q.front();q.pop(); cur++; for(int e=first[x];~e;e=nex[e]) { h[v[e]]=max(h[v[e]],h[x]+1); maxh=max(h[v[e]],maxh); if(--in[v[e]]==0)q.push(v[e]); } } if(cur!=n)return -1; return maxh+1; } void add_(int a,int b) { v[ecnt]=b; nex[ecnt]=first[a]; first[a]=ecnt++; } int main() { int n,m,i,j,x,y;char cc[10]; while(~scanf("%d%d",&n,&m)&&(n||m)) { memset(first,-1,sizeof first); memset(g,0,sizeof g); memset(_in,0,sizeof in); int flag=0,ans;ecnt=0; for(i=0;i<m;i++) { scanf("%s",cc); int x=cc[0]-'A'+1; int y=cc[2]-'A'+1; if(g[x][y])continue; if(!flag) { add_(x,y); _in[y]++; memcpy(in,_in,sizeof in); int ans1=topsort(n); if(ans1!=-1&&ans1==n)flag=1,ans=i+1; if(ans1==-1)flag=-1,ans=i+1; } } if(!flag)printf("Sorted sequence cannot be determined.\n"); else if(flag==-1)printf("Inconsistency found after %d relations.\n",ans); else { printf("Sorted sequence determined after %d relations: ",ans); for(i=0;i<n;i++) for(j=1;j<=n;j++) if(h[j]==i) { printf("%c",'A'-1+j); } printf(".\n"); } } return 0; }