题目链接:
http://poj.org/problem?id=1094
题意:
给出一连串关系,判断3个问题:
1.有唯一解并输出
2.是否有环
3.没有唯一解
注意1,3还要输出在第几个关系可以判断出来,可知3需要判断到最后,而1可能不需要。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <map>
using namespace std;
const int MAXN = 50;
map <string,int> letter;
int G[MAXN][MAXN], topo[MAXN], deep[MAXN];
int toposort(int n)
{
int i = 1,flag = 0;
int temp[40];
for(int hasaki = 1; hasaki <= n; hasaki++)
{
temp[hasaki] = deep[hasaki];
}
while(i <= n)
{
int judge = 0;
for(int j = 1; j <= n; j++)
{
if(!temp[j])
judge++;
}
if(!judge)
return 1;//有环
else if(judge > 1)
flag = 2;//不是唯一序
for(int j = 1; j <= n; j++)
{
if(!temp[j])
{
temp[j]--;
topo[i++] = j;
for(int k = 1; k <= n; k++)
{
if(G[j][k])
{
temp[k]--;
}
}
break;
}
}
}
return flag;
}
int main()
{
int n,m;
while(~scanf("%d %d", &n, &m))
{
if(!n && !m)break;
char str[5];
int flag = 0;
memset(deep,0,sizeof(deep));
memset(G,0,sizeof(G));
for(int i = 1; i<=m; i++)
{
scanf("%s", &str);
int a = str[0] - 'A' + 1, b = str[2] - 'A' + 1;
if(flag)continue;
G[a][b] = 1;
deep[b]++;
int ans = toposort(n);
if(ans == 1)
{
printf("Inconsistency found after %d relations.\n", i);
flag = 1;
}
else if(ans == 0)
{
printf("Sorted sequence determined after %d relations: ", i);
for(int k = 1; k <= n; k++)
printf("%c", topo[k] - 1 + 'A');
printf(".\n");
flag = 1;
}
}
if(!flag)
puts("Sorted sequence cannot be determined.");
}
}