题解 P1347 【排序】
zhouzihan_2004 · · 题解
本题是拓扑排序的一个变形,对于拓扑排序熟的人应该知道,关键是要判断有没有环和顺序是否可以定下来
还有一点,在输出的时候要特别注意格式,不要直接copy题目,要加一些改动,注意句号,本人就是因为没有注意句号wa了第九个点,改完以后就ac了
代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
#include<string.h>
using namespace std;
int n,m,h[27],indegree[27],gs,check,pd,Ans;
string in,ans;
struct EDGE
{
int next,target;
}edge[1001];
void Topsort()
{
pd=0;
gs=0;
queue<int>q;
for(int i=1;i<=n;i++)
if(indegree[i]==0)
{
gs++;
if(gs>=2) pd=1; //如果同一时间有两个及以上入度为0(它们可以以任意顺序摆放)的字母,说明无法确定顺序
q.push(i);
}
while(!q.empty()) //拓扑主体
{
gs=0;
int u=q.front();
q.pop();
ans+=char(u+'A'-1);
for(int i=h[u];i!=-1;i=edge[i].next)
{
indegree[edge[i].target]--;
Ans=max(Ans,i);
if(!indegree[edge[i].target])
{
q.push(edge[i].target);
gs++;
if(gs>=2) pd=1;
}
}
}
if(pd) cout<<"Sorted sequence cannot be determined.";
else cout<<"Sorted sequence determined after "<<Ans<<" relations: "<<ans<<".";
return ;
}
bool Check()
{
int Indegree[27];
for(int i=1;i<=n;i++)
Indegree[i]=indegree[i];
queue<int>q;
for(int i=1;i<=n;i++)
if(Indegree[i]==0) q.push(i);
while(!q.empty())
{
gs=0;
int u=q.front();
q.pop();
for(int i=h[u];i!=-1;i=edge[i].next)
{
Indegree[edge[i].target]--;
if(!Indegree[edge[i].target]) q.push(edge[i].target);
}
}
for(int i=1;i<=n;i++)
if(Indegree[i]) return true; //如果还有剩余的点(入度无法减为0),就说明有环
return false;
}
int main()
{
memset(h,-1,sizeof(h));
cin>>n>>m;
for(int i=1;i<=m;i++)
{
cin>>in;
int x=in[0]-'A'+1,y=in[2]-'A'+1;
edge[i].next=h[x];
edge[i].target=y;
h[x]=i;
indegree[y]++; //链式构图
if(Check()) //Check()判断是否有环
{
cout<<"Inconsistency found after "<<i<<" relations.";
return 0;
}
}
Topsort(); //基础拓扑排序
return 0;
}