题意:给m个大小关系,确定n个字母的大小关系,如果矛盾或者大小关系确定,那么就结束判断,否则继续判断。
解题思路:对于每次输入的信息,进行一次拓扑排序。
代码如下:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<cstring>
#include<string>
const int N = 30;
#define inf 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 10e-6
using namespace std;
int d[N],dd[N];
vector<int> a[N];
int res[N];
int n,m;
int tuopu()
{
queue<int> q;
int i,cnt = 0;
int flag = 0;
while(1)
{
for(i = 0; i < n; i++)
if(dd[i] == 0){
q.push(i);
dd[i] = -1;
}
if(q.size() > 1) flag = 1;
if(q.size() == 0) break;
int now = q.front();
q.pop();
res[cnt++] = now;
int len = a[now].size();
for(i = 0; i < len; i++)
dd[a[now][i]]--;
}
if(cnt < n) return 1;//矛盾
if(flag) return 2;
return 3;
}
int main()
{
while(scanf("%d%d",&n,&m))
{
if(n == 0 && m == 0) break;
memset(d,0,sizeof(d));
int i;
for(i = 0; i <= n; i++) a[i].clear();
int ans, k = 2;
for(i = 1; i <= m; i++)
{
char s[10];
scanf("%s",s);
if(k == 2)
{
int u = s[0] - 'A';
int v = s[2] - 'A';
d[v]++;
a[u].push_back(v);
for(int j = 0; j < n; j++)
dd[j] = d[j];
k = tuopu();
if(k != 2)
ans = i;
}
}
if(k == 1) printf("Inconsistency found after %d relations.\n",ans);
else if(k == 2) printf("Sorted sequence cannot be determined.\n");
else{
printf("Sorted sequence determined after %d relations: ",ans);
for(i = 0; i < n; i++)
printf("%c",(char)('A'+res[i]));
printf(".\n");
}
}
return 0;
}