题目思路
题目中的A>B 转化为 g[A][B] = 1 然后每次输入一次就进行一次floyd
再check一下是否能确定有无解 对于每个i 都没有d[i][i] = 1 或者 d[i][j]=d[j][i]=1
如果能确定 更新一下t 最后方便输出
然后对于从小到大输出顺序可以遍历n次每次找最小的那个即无法找到d[i][j]=1的i值为当前最小值
代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 30;
int n, m;
bool 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])
return 2;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < i; 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 i + 'A';
}
}
}
}
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', b = str[2] - 'A';
if (!type)
{
d[a][b] = 1;
floyd();
type = check();
if (type) t = i;
}
}
if (!type) puts("Sorted sequence cannot be determined.");
else if (type == 2) printf("Inconsistency found after %d relations.\n", t);
else
{
memset(st, 0, sizeof st);
printf("Sorted sequence determined after %d relations: ", t);
for (int i = 0; i < n; i ++ ) printf("%c", get_min());
printf(".\n");
}
}
return 0;
}