POj 1094 Sorting it All Out
2010-11-08 20:57
417 查看
解题思路:每增加一个点,均判断其拓扑排序,如果首先发现可以排序的情况,则不管后面的输入情况是否出现环。
#include <iostream> #include <stack> using namespace std; int main() { int n, m, t, L; char u, v, ch, seq[26]; bool edge[26][26], comeOut[26]; int degree[26], tdeg[26]; stack<int>temp; string str; bool flag1, flag2, flag; while (cin >> n >> m && n * n + m * m) { while (!temp.empty()) temp.pop(); flag1 = flag2 = true; t = 0; fill(&edge[0][0], &edge[25][26], false); memset(degree, 0, sizeof(int) * 26); memset(comeOut, 0, sizeof(bool) * 26); for (int i = 1; i <= m; i++) { cin >> u >> ch >> v; if (!(flag1 && flag2)) continue; if (!edge[u - 'A'][v - 'A']) { if(!comeOut[u - 'A']) { t++; comeOut[u - 'A'] = true; } if (!comeOut[v - 'A']) { t++; comeOut[v - 'A'] = true; } edge[u - 'A'][v - 'A'] = true; degree[v - 'A']++; flag = (t == n) ? true : false; for (int j = 0; j < n; j++) { tdeg[j] = degree[j]; if (comeOut[j] && tdeg[j] == 0) temp.push(j); } if (flag && temp.size() > 1) flag = false; int index = 0; while (!temp.empty()) { int ts = temp.top(); seq[index++] = 'A' + ts; temp.pop(); for (int j = 0; j < n; j++) if (edge[ts][j]) { tdeg[j]--; if (tdeg[j] == 0) temp.push(j); } if (flag && temp.size() > 1) flag = false; } for (int j = 0; (j < n) && flag2; j++) if (tdeg[j] != 0) { L = i; flag2 = false; } if (t == n && flag && flag2) { L = i; flag1 = false; } } } if (!flag1) { cout << "Sorted sequence determined after " << L << " relations: "; for (int i = 0; i < n; i++) cout << seq[i]; cout << "." << endl; } else if(!flag2) cout << "Inconsistency found after " << L << " relations."<<endl; else cout << "Sorted sequence cannot be determined." << endl; } return 0; }
相关文章推荐
- POJ 1094 Sorting It All Out (拓扑排序)
- POJ_1094_sorting it all out_拓扑排序
- POJ 1094 Sorting It All Out(拓扑排序)
- POJ 1094 Sorting It All Out 拓扑排序
- poj 1094 Sorting it all out
- 拓扑排序 附POJ 1094 Sorting It All Out 解题报告
- POJ1094 Sorting It All Out
- poj 1094 Sorting It All Out_拓扑排序
- POJ1094——Sorting It All Out
- poj 1094 Sorting It All Out(拓扑排序 + 邻接表)
- POJ-1094 Sorting It All Out 解题报告
- 【POJ 1094】Sorting It All Out (邻接表)
- Sorting It All Out POJ - 1094 拓扑排序
- POJ1094 Sorting It All Out 拓扑排序(深搜)
- poj 1094 Sorting It All Out(拓扑排序)
- POJ 1094 Sorting It All Out 拓扑排序
- POJ-1094-Sorting It All Out(拓扑排序)
- poj 1094 Sorting It All Out (拓扑排序)
- Sorting It All Out poj 1094(判断严格小于关系&判断是否有环)
- POJ 1094 Sorting It All Out(拓扑序列)