Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 22332 | Accepted: 7705 |
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.
// 首先。有拓扑排序检查是不是有环的存在,要是没有环的话,用flody传递闭包
再判断序列是不是唯一的。
而判断序列是不是唯一的方法是:
n个结点的出度分别是0,1,2,3,4...n-1,是的话就说明是唯一的
代码:
#include<cstdio> #include<iostream> #include<queue> #include<cmath> #include<cstring> #include<string> #include<algorithm> #include<stack> using namespace std; typedef long long LL; #define clr(x) memset(x,0,sizeof(x)); #define sf scanf #define pf printf int map[35][35]; int path[35]; bool vis[35]; int cnt[35]; int N,M; const int INF=1<<29; void flody(){//传递闭包 for(int k2=0;k2<N;k2++) for(int i1=0;i1<N;i1++) for(int j3=0;j3<N;j3++){ if(map[k2][i1]&&map[i1][j3]) map[k2][j3]=1; } } void updata(int u){ for(int i=0;i<N;i++){ if(map[u][i]) --cnt[i]; } cnt[u]--; } bool topSort(){ clr(cnt); for(int i=0;i<N;i++) for(int j=0;j<N;j++){ if(map[i][j]) ++cnt[j]; } for(int i=0;i<N;i++){ int u=-1; for(int j=0;j<N;j++){ if(!cnt[j]){ u=j; break; } } if(u==-1) return true; path[i]=u; updata(u); } return false; } bool judge(){ clr(vis); for(int i=0;i<N;i++){ int out=0; for(int j=0;j<N;j++){ if(map[i][j]) out++; } if(vis[out]) return false; vis[out]=true; } return true; } int main(){ while(sf("%d%d",&N,&M)!=EOF&&N+M){ bool flag=false; char str[5]; clr(map); for(int i=1;i<=M;i++){ sf("%s",&str); if(flag) continue; int x=str[0]-'A'; int y=str[2]-'A'; if(map[x][y]) continue; map[x][y]=1; if(topSort()){ pf("Inconsistency found after %d relations.\n",i); flag=true; continue; } flody(); if(judge()){ pf("Sorted sequence determined after %d relations: ",i); for(int j=0;j<N;j++) pf("%c",path[j]+'A'); pf(".\n");flag=true; } } if(!flag) pf("Sorted sequence cannot be determined.\n"); } return 0; }