POJ 1094 Sorting It All Out

拓扑排序,加入一个关系后就判断一次,注意判断排序不能确定后不能马上跳过,还要继续看看会不会形成环

C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>

using namespace std;

bool arr[26][26];
int n, m;
int degree[26];
char ans[30];

int topoSort(){
int ret = 1;
int pos = 0;
int tmpDegree[26];
memcpy(tmpDegree, degree, sizeof(tmpDegree));
queue<int> q;
for(int i = 0; i < n; i++)
if(degree[i] == 0)
q.push(i);
while(!q.empty()){
if(q.size() > 1)
ret = 0;
int cur = q.front();
q.pop();
ans[pos++] = cur + 'A';
for(int i = 0; i < n; i++){
if(arr[cur][i]){
tmpDegree[i]--;
if(tmpDegree[i] == 0)
q.push(i);
}
}
}
if(pos < n){
return -1;
}
ans[pos] = '\0';
return ret;
}

int main(){
char ch[4];
bool flag = false;
while(~scanf("%d%d", &n, &m) && n != 0){
memset(arr, 0, sizeof(arr));
memset(degree, 0, sizeof(degree));
flag = false;
for(int i = 0; i < m; i++){
scanf("%s", ch);
arr[ch[0]-'A'][ch[2]-'A'] = true;
if(flag) continue;
degree[ch[2]-'A']++;
int topo = topoSort();
if(topo == 1){
flag = true;
printf("Sorted sequence determined after %d relations: %s.\n", i+1, ans);
}else if(topo == -1){
flag = true;
printf("Inconsistency found after %d relations.\n", i+1);
}
}
if(!flag)
printf("Sorted sequence cannot be determined.\n");
}
return 0;
}