POJ 1094 Sorting It All Out

版权声明:听说这里让写版权声明~~~ https://blog.csdn.net/m0_37691414/article/details/82083256

解析:拓扑排序。(不喜欢这道题)

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int  e[27][27], indegree[27], q[27];
int solve(int n){
	int  k = 0, temp[27], flag = 1;
	for(int i = 1; i <= n; ++i)	temp[i] = indegree[i];
	for(int i = 1; i <= n; ++i){
		int m = 0, u;
		for(int j = 1; j <= n; ++j)
			if(temp[j] == 0)
				m++, u = j;
		if(m == 0)	return 0;
		if(m > 1)	flag = -1;
		q[k++] = u;
		temp[u] = -1;
		for(int j = 1; j <= n; ++j)
			if(e[u][j] == 1)	temp[j]--;
	}
	return flag;
}
int main(){
	int n, m;
	char str[5];
	while(~scanf("%d%d", &n, &m), n, m){
		gets(str);
		memset(e, 0, sizeof(e));
		int flag = false;
		memset(indegree, 0, sizeof(indegree));
		for(int i = 1; i <= m; ++i){
			scanf("%s", str);
			if(flag) continue;
			int x = str[0] - 'A' + 1;
			int y = str[2] - 'A' + 1;
			e[x][y] = 1;
			indegree[y]++;
			int s = solve(n);
			if(s == 0){
				printf("Inconsistency found after %d relations.\n", i);
				flag = true;
			}
			if(s == 1){
				printf("Sorted sequence determined after %d relations: ",i);
                for(int j = 0;j < n; j++)
                    printf("%c", q[j]+'A'-1);
                printf(".\n");
                flag = 1;
			}
		}
		if(flag == false)	printf("Sorted sequence cannot be determined.\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37691414/article/details/82083256