POJ 1094 Sorting It All Out 拓扑排序

题意:输入n, m,n表示26个大写字母组成的字母表中前n个字母,m表示将输入m对字母的大小关系式,(ch1 < ch2)问根据输入多少个关系式时能惟一确定这n个字母有可能出现的关系,共有3 种情况:

(1)如果出现ch1 < ch2同时又有ch1 > ch2则表示这n个字母是inconsistency。

(2)能确定有惟一这n个的字母的拓扑序。

(3)不能根据输入的m对关系确定这n个字母逻辑大小的关系。

题解:
(1)用d[i][j]表示第字符'A'+ i和字符‘A' + j的关系, ‘A' + i < 'A' + j时,d[i][j] = true,否则为false;

(2)当出现d[i][j] 和 d[j][i]同时为true时,出现矛盾,可以判定inconsistency.

(3)记录d[i][j] = true(0 <= i < n && 0 <= j < n) 的关系式有count个时,当count == n * (n - 1) /2时,可以确定有惟一的拓扑序。

#include <cstring>
#include <iostream>
using namespace std;

int m, n, find, step;
int map[30][30],in[30];
char str[5],ans[30];

bool loop()   /* 判断是否有环 */
{
	int i, j, k;
	for (  k = 0; k < m; k++ )
		for ( i = 0; i < m; i++ )
			for ( j = 0; j < m; j++ )
				if ( map[i][k] && map[k][j] )
					map[i][j] = 1;
	for ( i = 0; i < m; i++ )
		if ( map[i][i] )
			return true;
	return false;
}

int topo ()
{
	if ( loop() ) return 3;
	memset(in,0,sizeof(in));
	memset(ans,0,sizeof(ans));
	for ( int i = 0; i < m; i++ )
	{
		for ( int j = 0; j < m; j++ )
			if ( map[j][i] )
				in[i]++;
		if ( ans[in[i]] == 0 )
			ans[in[i]] = i+'A';
		else return 2;
	}
	ans[m] = '\0';
	return 1; 
}


int main()
{
	while ( scanf("%d%d",&m,&n) && m+n )
	{
		find = step = 0;
		memset(map,0,sizeof(map));
		for ( int i = 1; i <= n; i++ )
		{
			scanf("%s",str);
			map[str[0]-'A'][str[2]-'A'] = 1;
			if ( ! find )
			{
				int temp = topo();
				if ( temp == 3 )
				{
					find = 3; step = i;
				}
				else if ( temp == 1 )
				{
					find = 1; step = i;
				}
				else if ( i == n )
					find = 2;
			}
		}

		if ( find == 1 )
			printf("Sorted sequence determined after %d relations: %s.\n", step, ans);
		else if ( find == 2 )
			printf("Sorted sequence cannot be determined.\n");
		else if ( find == 3 )
			printf("Inconsistency found after %d relations.\n", step);
	}
	return 0;
}


你可能感兴趣的:(POJ 1094 Sorting It All Out 拓扑排序)