poj 1094 Sorting It All Out

http://poj.org/problem?id=1094

感觉还是挺好的一个题的,虽说是看的小媛的思路;

题意:判断给出的一些字母的先后顺序,进行拓扑排序,看看是否有序;

思路:用flord判断环还是挺好的,然后拓扑排序判断序列的排序关系;

代码:

View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
int n = 0;
int m = 0;
int map[30][30] = {0};
int flag = 0;
int huan()
{
for(int i = 0;i < n; ++i)
for(int j = 0;j < n; ++j)
for(int k = 0;k < n; ++k)
if(map[j][i]&&map[i][k])
map[j][k] = 1;
for(int i = 0;i < n; ++i)
if(map[i][i])
return 1;
return 0;
}
int find(int u)
{
int visit[30] = {0};
int in[30] = {0};
char ans[30] = {0};
for(int i = 0;i < n; ++i)
for(int j = 0;j < n; ++j)
if(map[i][j])
++in[j];
int q = 0;
for(int i = 0;i < n;++i)
{
int num = 0;
int temp = 0;
for(int j = 0;j < n; ++j)
if(!visit[j] && in[j] == 0)
{
ans[q++] = j + 'A';
++num;
visit[j] = 1;
temp = j;
}
if(num > 1)
return 0;
for(int k = 0;k < n; ++k)
if(map[temp][k])
--in[k];
}
printf("Sorted sequence determined after %d relations: ",u);
for(int i = 0;i < q; ++i)
printf("%c",ans[i]);
printf(".\n");
return 1;
}
int main()
{
while(scanf("%d%d",&n,&m),n&&m)
{
memset(map,0,sizeof(map));
char str[4] = {NULL};
flag = 0;
for(int i = 1;i <= m; ++i)
{
scanf("%s",str);
map[str[0]-'A'][str[2]-'A'] = 1;
if(flag)
continue;
if(huan())
{
flag = 1;
printf("Inconsistency found after %d relations.\n",i);
continue;
}
if(find(i))
{
flag = 2;
continue;
}
}
if(flag == 0)
printf("Sorted sequence cannot be determined.\n");
}
}



你可能感兴趣的:(sort)