qzezoj 1667 Sorting It All Out
题面传送门
这个对于每个边跑拓扑序即可,如果有环那么不可行,如果两个字母拓扑序相同也不可行。
代码实现:
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,k,x,y,z,in[139],flag,out[139],flags[139],sh,now,cur,pus,tot,topo[139];
struct yyy{int to,z;}tmp;
struct ljb{
int head,h[139];
yyy f[10039];
inline void add(int x,int y){
f[++head]=(yyy){y,h[x]};
h[x]=head;
}
}s;
char _s,sf,sss;
queue<int > q;
int main(){
register int i,j;
scanf("%d",&n);
while(n){
memset(s.h,-1,sizeof(s.h));
memset(in,0,sizeof(in));
s.head=pus=0;
scanf("%d",&m);
for(i=1;i<=m;i++){
_s=getchar();
while(_s<'A'||_s>'Z')_s=getchar();
sss=getchar();
sf=getchar();
if(pus) continue;
if(sss=='>') swap(sf,_s);
s.add(_s-'A'+1,sf-'A'+1);
in[sf-'A'+1]++;
flag=sh=0;
for(j=1;j<=n;j++) out[j]=in[j];
for(j=1;j<=n;j++) if(!out[j]){q.push(j);topo[j]=1;}
while(!q.empty()){
now=q.front();
q.pop();
flags[++sh]=now;
cur=s.h[now];
while(cur!=-1){
tmp=s.f[cur];
out[tmp.to]--;
if(!out[tmp.to]) q.push(tmp.to),topo[tmp.to]=topo[now]+1;
cur=tmp.z;
}
}
flag=0;
for(j=1;j<=n;j++) if(out[j]) {flag=1;break;}
if(flag){
printf("Inconsistency found after %d relations.\n",i);
pus=1;continue;
}
sort(topo+1,topo+n+1);
for(j=2;j<=n;j++) if(topo[j]==topo[j-1]){flag=1;break;}
if(!flag){
printf("Sorted sequence determined after %d relations: ",i);
for(j=1;j<=n;j++) putchar(flags[j]+'A'-1);
printf(".\n");pus=1;continue;
}
}
if(!pus) printf("Sorted sequence cannot be determined.\n");
scanf("%d",&n);
}
}