Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
拓扑排序 0ms~~#include<cstdio> #include<cstring> const int N=30; int n,m; char str[5]; struct qq { int y; int last; }s[N*N]; int last[N],num; int ttt[N]; void init (int x,int y) { num++; ttt[y]++; s[num].y=y; s[num].last=last[x]; last[x]=num; return ; } int cnt,top[N]; int tt[N]; int ooo;//这一次有多少个元素进栈 //假如ooo每一次都是1,那么说明已经有序了 int q[N],num1;//假如有序则记录路径 int solve () { cnt=0;ooo=0;num1=0; for (int u=1;u<=n;u++) tt[u]=ttt[u]; for (int u=1;u<=n;u++) if (tt[u]==0) { q[++num1]=u; top[++cnt]=u; ooo++; } bool tf=true;//是否有序 while (cnt>0) { int x=top[cnt--]; if (ooo>1) tf=false; ooo=0; for (int u=last[x];u!=-1;u=s[u].last) { int y=s[u].y; tt[y]--; if (tt[y]==0) { q[++num1]=y; top[++cnt]=y; ooo++; } } } if (ooo>1) tf=false; if (num1!=n) return 0; if (tf==true) return 1; return 2; } void Ready() { num=0; memset(last,-1,sizeof(last)); memset(ttt,0,sizeof(ttt)); return ; } int main() { while (true) { scanf("%d%d",&n,&m); if (n==0&&m==0) break; Ready(); bool ok=false;//是否已经出现过答案 for (int u=1;u<=m;u++) { scanf("%s",str); if (ok==true) continue; int a=str[0]-'A'+1,b=str[2]-'A'+1; init(a,b); int s=solve(); if(s==0)//有环 { printf("Inconsistency found after %d relations.\n",u); ok=true; } if(s==1)//有序 { printf("Sorted sequence determined after %d relations: ",u); for(int j=1;j<=n;j++) printf("%c",q[j]+'A'-1); printf(".\n"); ok=true; } } if (ok==false) printf("Sorted sequence cannot be determined.\n"); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator