标签:拓扑排序
拓扑排序
输出第一次成功排序的位置及顺序(能顺利拓扑并在拓扑中不存在同级)
或者
第一个出现与之前给出条件相悖的位置(拓扑过程中出现间断)
坑点是出现任何一种情况就out
代码如下
#include <iostream>
using namespace std;
int in[26],inn[26],n;
int mp[26][26];
int Topo(int op)
{
int i,j,k,f = 1;
for(i = 0; i < n; ++i)
inn[i] = in[i];
for(i = 0; i < n; ++i)
{
k = -1;
for(j = 0; j < n; ++j)
{
if(!inn[j])
{
if(k != -1) f = 0;
k = j;
}
}
j = k;
if(j == -1) return -1;
if(op) putchar(‘A‘+j);
inn[j]--;
for(k = 0; k < n; ++k)
inn[k] -= mp[j][k];
}
if(op)
puts(".");
return f;
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int f,m,i,a,b,x;
char st[5];
while(~scanf("%d %d",&n,&m) && n && m)
{
memset(mp,0,sizeof(mp));
memset(in,0,sizeof(in));
f = 0;
x = -1;
for(i = 1; i <= m; ++i)
{
scanf("%s",st);
a = st[0]-‘A‘;
b = st[2]-‘A‘;
if(st[1] == ‘>‘)
{
a += b;
b = a-b;
a -= b;
}
if(f) continue;
mp[a][b]++;
in[b]++;
f = Topo(0);
x = i;
}
if(!f) puts("Sorted sequence cannot be determined.");
else if(f == -1) printf("Inconsistency found after %d relations.\n",x);
else
{
printf("Sorted sequence determined after %d relations: ",x);
Topo(1);
}
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:拓扑排序
原文地址:http://blog.csdn.net/challengerrumble/article/details/46767031