本来打算当打了个拓扑的板子
后来发现并不只是个板子
差不多 管他呢
#include<cstdio> #include<cstring> #include<iostream> #include<queue> #include<algorithm> #define rint register int using std::queue; using std::cout; using std::endl; template <class T> inline void read(T &X) { X=0;int W=0;char ch=0; while(!isdigit(ch))W|=ch=='-',ch=getchar(); while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar(); X=W?-X:X;return; } int n,m,head[30],CNT=0,in[30],IN[30],cnt=0,Cnt=0,vis[30],ans[30]; struct node{int to,next;}edge[50]; queue<int> q; void add(int u,int v) { ++in[v]; edge[++Cnt].to=v; edge[Cnt].next=head[u]; head[u]=Cnt; } int tp() { int pd=0,pd2=0;cnt=0; for(rint i=1;i<=26;++i) { IN[i]=in[i]; if(!IN[i] && vis[i]) { if(!pd)pd=1; else pd2=1; q.push(i); ans[++cnt]=i; } } if(q.empty())return 1; while(!q.empty()) { int u=q.front();q.pop();pd=0; for(rint i=head[u];i;i=edge[i].next) { --IN[edge[i].to]; if(!IN[edge[i].to]) { if(!pd)pd=1; else pd2=1; q.push(edge[i].to); ans[++cnt]=edge[i].to; } } } if(cnt!=CNT)return 1; if(pd2)return 2; return 0; } int main() { read(n),read(m); for(rint i=1;i<=m;++i) { char a[5]; scanf("%s",a); int u=a[0]-64,v=a[2]-64; add(u,v); if(!vis[u])vis[u]=1,CNT++; if(!vis[v])vis[v]=1,CNT++; int tps=tp(); if(tps==1) { printf("Inconsistency found after %d relations.",i); return 0; } if(cnt==n && !tps) { printf("Sorted sequence determined after %d relations: ",i); for(rint j=1;j<=cnt;++j)printf("%c",ans[j]+64); printf(".") ; return 0; } } printf("Sorted sequence cannot be determined."); return 0; }