Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 38379 | Accepted: 13534 |
Description
Input
Output
Sorted sequence determined after xxx relations: yyy...y.
Sorted sequence cannot be determined.
Inconsistency found after xxx relations.
where xxx is the number of relations processed at the time either a sorted sequence is determined or an inconsistency is found, whichever comes first, and yyy...y is the sorted, ascending sequence.
Sample Input
4 6
A<B
A<C
B<C
C<D
B<D
A<B
3 2
A<B
B<A
26 1
A<Z
0 0
Sample Output
Sorted sequence determined after 4 relations: ABCD.
Inconsistency found after 2 relations.
Sorted sequence cannot be determined.
Source
#include <iostream> #include <cstring> using namespace std; int in[30]; //入度 int out[30]; //输出序列 int map[30][30]; //有向图 int TopoSort(int n){ int ct = 0, cpin[30]; int flag = 1; for(int i = 0; i < n; i++){ cpin[i] = in[i]; } while(ct < n){ int p = -1, m = 0; for(int i = 0; i < n; i++){ if(cpin[i] == 0){ p = i; m++; } } if(m == 0){ return -1; //有环 } if(m > 1){ // return 0; //无法判断 flag = 0; //得出不能判断只有还有检测,因为可能后面可能有环 } out[ct++] = p; cpin[p] = -1; for(int i = 0; i < n; i++){ if(map[p][i]){ cpin[i]--; } } } return flag; //排好序了 } int main(){ std::ios::sync_with_stdio(false); int n, m; char x, y; char ch; while(cin >> n >> m && (n != 0 && m != 0)){ memset(in, 0, sizeof(in)); memset(map, 0, sizeof(map)); int flag = 1; for(int i = 0; i < m; i++){ cin >> x >> ch >> y; if(flag == 0) continue; //注意就算前面已经判断出结果,也要输入完,但不需要判断了 if(map[x - 'A'][y - 'A'] == 0){ map[x - 'A'][y - 'A'] = 1; in[y - 'A']++; int s = TopoSort(n); if(s == -1){ cout << "Inconsistency found after "; cout << i + 1; cout << " relations." << endl; flag = 0; } if(s == 1){ cout << "Sorted sequence determined after "; cout << i + 1; cout << " relations: "; for(int i = 0; i < n; i++){ cout << char(out[i] + 'A'); } cout << "." << endl; flag = 0; } } } if(flag){ cout << "Sorted sequence cannot be determined." << endl; } } return 0; }