Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 32275 | Accepted: 11210 |
Description
Input
Output
Sorted sequence determined after xxx relations: yyy...y.
Sorted sequence cannot be determined.
Inconsistency found after xxx relations.
where xxx is the number of relations processed at the time either a sorted sequence is determined or an inconsistency is found, whichever comes first, and yyy...y is the sorted, ascending sequence.
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.
题目大意:给你字母表的前N个字母以及M个他们之间的关系,问最终是全序,偏序,还是出现矛盾。
思路分析:有向图,很明显拓扑排序,这是我做的第二道拓扑排序的题目,在学习图论之前一直以为拓扑
排序就是单纯的一种排序方式,现在才知道它是图论的一部分,有向图,因为本题不仅要求输出结果,还要判断
在输入第几个顺序时得出的结果,因此每输入一组数据就要进行一拓扑排序,拓扑排序本质上一种偏序排序,
当然在一定情况下会出现全序的特殊情况,j!=n,就说明有向图的构建过程中出现了环,有可能直接是反向环,
也有可能是绕一圈后回来,如果队列中元素>1,说明队列中存在两个以上优先级相同的元素,即有向图是偏序的。
不说了,上代码,本题对于拓扑排序的理解还是十分有用的。
代码:
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=27;
int indegree[maxn],ans[maxn],graph[maxn][maxn];
int n,m;
int topsort()
{
int flag=0;
int in[maxn];
int j=0;
memcpy(in,indegree,sizeof(indegree));//一定要重新定义一个数组,防止对主函数中indegree数组产生影响
queue<int> q;
for(int i=0;i<n;i++)
{
if(in[i]==0) q.push(i);//将入度为0的点放入队列
}
while(!q.empty())
{
if(q.size()>1) flag=1;
int t=q.front();
q.pop();//记得弹出
ans[j++]=t;
for(int i=0;i<n;i++)
{
if(graph[t][i])
{
in[i]--;
if(in[i]==0) q.push(i);
}
}
}
if(j!=n)//不能拓扑排序 ,存在环
return 1;
else if(flag==1) return 2;
else return 0;
}
int main()
{
char s[5];
while(scanf("%d%d",&n,&m)&&(n||m))
{
int incon=0,detmin=0;
memset(graph,0,sizeof(graph));
memset(indegree,0,sizeof(indegree));
for(int i=1;i<=m;i++)
{
scanf("%s",s);
if(detmin||incon) continue;
int a=s[0]-'A';
int b=s[2]-'A';
if(graph[a][b]==0)
{
graph[a][b]=1;
indegree[b]++;
}
int res=topsort();
if(res==0)
{
detmin=1;
printf("Sorted sequence determined after %d relations: ",i);
for(int i=0;i<n;i++)
printf("%c",ans[i]+'A');
printf(".\n");
}
if(res==1)
{
incon=1;
printf("Inconsistency found after %d relations.\n",i);
}
}
if(!incon&&!detmin) printf("Sorted sequence cannot be determined.\n");
}
}