按照a < b则在a和b中连一条长度为1的边建图,d[a][b] = 1表示a小于b,每加入一组数据跑一边floyd,(实际上就是动态规划更新一下每个点能到的点),判断三种情况:
存在d[i][i] = 1,i 大于 i 说明存在矛盾。
存在d[i][j] = 0 && d[j][i] = 0说明无法判断 i 和 j 的大小,无法确定关系。
否则可以确定,输出大小可以类似于拓扑排序的思想输出。
#include<bits/stdc++.h>
using namespace std;
const int N = 30;
int n,m;
int d[N][N];
bool st[N];
void floyd()
{
for(int k = 0; k < n; k ++ )
for(int i = 0; i < n; i ++ )
for(int j = 0; j < n; j ++ )
d[i][j] |= d[i][k] && d[k][j];
}
int check()
{
for(int i = 0; i < n; i ++ )
if(d[i][i] == 1)
return 2;
for(int i = 0; i < n; i ++ )
for(int j = i + 1; j < n; j ++ )
if(!d[i][j] && !d[j][i])
return 0;
return 1;
}
char get_min()
{
for(int i = 0; i < n; i ++ )
if(!st[i])
{
bool flag = true;
for(int j = 0; j < n; j ++ )
{
if(!st[j] && d[j][i])
{
flag = false;
break;
}
}
if(flag)
{
st[i] = true;
return 'A' + i;
}
}
}
int main()
{
while(cin>>n>>m,n || m)
{
memset(d,0,sizeof(d));
int type = 0,t;
for(int i = 1; i <= m; i ++ )
{
char str[5];
cin>>str;
int a = str[0] - 'A';
int b = str[2] - 'A';
if(!type)
{
d[a][b] = 1;
floyd();
type = check();
if(type)
t = i;
}
}
if(type == 2)
cout<<"Inconsistency found after "<<t<<" relations."<<'\n';
else if(type == 0)
cout<<"Sorted sequence cannot be determined."<<'\n';
else
{
memset(st,false,sizeof(st));
cout<<"Sorted sequence determined after "<<t<<" relations: ";
for(int i = 0; i < n; i ++ )
cout<<get_min();
cout<<"."<<'\n';
}
}
return 0;
}