标签:
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.
套模板硬上
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <queue> #include <vector> #include <iomanip> #include <math.h> #include <map> using namespace std; #define FIN freopen("input.txt","r",stdin); #define FOUT freopen("output.txt","w",stdout); #define INF 0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 typedef long long LL; const int MAXN=1e5+5; struct Edge{ int v,nxt; }E[MAXN*2]; int Head[MAXN],erear; int IN[MAXN],P[MAXN],sz; int temp[MAXN]; int n,m,sum; int flag,ed; bool con; void edge_init(){ erear=0; memset(Head,-1,sizeof(Head)); memset(IN,0,sizeof(IN)); sum=0; con=0; } void edge_add(int u,int v){ E[erear].v=v; E[erear].nxt=Head[u]; Head[u]=erear++; } int topsort(){ sz=0; queue<int>Q; for(int i=0;i<n;i++){ if(!IN[i]) Q.push(i); } bool sign=0; while(!Q.empty()){ if(Q.size()>=2) sign=1; int u=Q.front(); Q.pop(); P[sz++]=u; for(int i=Head[u];~i;i=E[i].nxt){ int v=E[i].v; IN[v]--; if(!IN[v]) Q.push(v); } } if(sz<n){ //printf("invalid\n"); return 1; }else if(sign){ //printf("multi ans\n"); return 2; }else{ return 3; } /*for(int i=0;i<sz;i++){ if(i==0) printf("%d",P[i]); else printf(" %d",P[i]); } printf("\n");*/ } int main() { //FIN while(~scanf("%d%d",&n,&m)) { if(n==0&&m==0) break; edge_init(); flag=2; char op[10]; for(int i=1;i<=m;i++){ scanf("%s",op); if(con) continue; int u=(int)op[0]-‘A‘; int v=(int)op[2]-‘A‘; if(op[1]==‘>‘){ edge_add(u,v); IN[v]++; } else{ edge_add(v,u); IN[u]++; } memcpy(temp,IN,sizeof(IN)); flag=topsort(); memcpy(IN,temp,sizeof(temp)); sum=i; if(flag!=2){ ed=i; con=true; } } if(flag==3){ printf("Sorted sequence determined after %d relations: ", ed); for(int i=sz-1; i>=0; --i) printf("%c",P[i]+‘A‘); printf(".\n"); } else if(flag==1){ printf("Inconsistency found after %d relations.\n",ed); } else{ printf("Sorted sequence cannot be determined.\n"); } } return 0; }
POJ 1094 Sorting It All Out 拓扑排序
标签:
原文地址:http://www.cnblogs.com/Hyouka/p/5751218.html