Sorting It All Out (POJ - 1094 ,Floyd 传闭包)

mac2024-11-16  6

一.问题回顾:

Sorting It All Out (POJ - 1094 ,拓扑排序 + 链式向前星存图)

由于之前已经写过拓扑排序解法,这里不在详谈.

二.分析:

Floyd 传闭包

注意:要先判矛盾.

详见代码.

三.代码实现:

#include <bits/stdc++.h> using namespace std; const int M = (int)26; int n, m; char u, v; bool flag; bool dis[M][M]; int Floyed() { for(int k = 0; k < n; ++k) { for(int i = 0; i < n; ++i) { if(dis[i][k]) { for(int j = 0; j < n; ++j) { dis[i][j] |= (dis[i][k] & dis[k][j]); if(i != j && (dis[i][j] & dis[j][i])) return -1; } } } } for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(i != j && !(dis[i][j] | dis[j][i])) return 0; } } return 1; } int cnt[M]; vector < pair<int, int> > ans; void print_order() { ans.clear(); memset(cnt, 0, sizeof(cnt)); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(dis[i][j]) ++cnt[j]; } } for(int i = 0; i < n; ++i) ans.push_back(make_pair(cnt[i], i)); sort(ans.begin(), ans.end()); for(auto x : ans) putchar(x.second + 'A'); } int main() { while(~scanf("%d %d", &n, &m) && (n + m)) { flag = 0; memset(dis, 0, sizeof(dis)); for(int i = 1; i <= m; ++i) { getchar(); scanf("%c<%c", &u, &v); if(flag) continue; u -= 'A', v -= 'A'; dis[u][v] = 1; int ans = Floyed(); if(ans == 1) { flag = 1; printf("Sorted sequence determined after %d relations: ", i); print_order(); printf(".\n"); } else if(ans == -1) { flag = 1; printf("Inconsistency found after %d relations.\n", i); } } if(!flag) printf("Sorted sequence cannot be determined.\n"); } return 0; }

 

最新回复(0)