通过看加入队列的元素个数和总元素个数判断有无环
通过记录队列访问层数得到最长链的长度
#include<bits/stdc++.h>
using namespace std;
int read() {
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
return x*f;
}
void write(int x) {
if(x<0) putchar('-'),x=-x;
if(x>9) write(x/10);
putchar(x%10+'0');
}
int n,m,uu,vv,sum;
string kk;
struct edge{
int from,to,nex;
}e[650];
int head[30],in[30];
void add(int kk)
{
e[kk]=(edge){uu,vv,head[uu]};
head[uu]=kk;
}
struct one{
int x,fl;
};
set<int>s;
int f=0;
queue<one>q;
queue<int>q1;
void solve()
{
for(int i=1;i<=26;++i)
{
if(in[i]==0&&s.count(i))
{
q1.push(i);
printf("%c",'A'+i-1);
}
}
int now;
while(!q1.empty())
{
now=q1.front();
q1.pop();
for(int i=head[now];i!=-1;i=e[i].nex)
{
in[e[i].to]--;
if(in[e[i].to]==0)
{
q1.push(e[i].to);
printf("%c",'A'+e[i].to-1);
}
}
}
}
void topu(int pp)
{
while(!q.empty())
q.pop();
int summ=0;
int ans=0;
one now;
int fln;
int inn[30];
for(int i=1;i<=26;++i)
{
inn[i]=in[i];
if(in[i]==0&&s.count(i))
{
q.push((one){i,1});
summ++;
ans=1;
}
}
while(!q.empty())
{
now=q.front();
q.pop();
fln=now.fl;
for(int i=head[now.x];i!=-1;i=e[i].nex)
{
inn[e[i].to]--;
if(inn[e[i].to]==0)
{
summ++;
q.push((one){e[i].to,fln+1});
ans=max(ans,fln+1);
}
}
}
if(summ!=sum)
{
f=1;
printf("Inconsistency found after %d relations.",pp);
}
else if(ans==n)
{
f=1;
printf("Sorted sequence determined after %d relations: ",pp);
solve();
printf(".");
}
}
int main ()
{
n=read(),m=read();
memset(head,-1,sizeof(head));
for(int i=1;i<=m;++i)
{
cin>>kk;
uu=kk[0]-'A'+1;
vv=kk[2]-'A'+1;
add(i);
s.insert(uu);
s.insert(vv);
sum=s.size();
in[vv]++;
if(!f)
topu(i);
}
if(!f)
{
printf("Sorted sequence cannot be determined.");
}
return 0;
}