[题目链接]
http://poj.org/problem?id=1094
[算法]
floyed传递闭包
[代码]
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXC 30 int i,j,k,n,m,pos; int cnt[30]; int d[MAXC][MAXC]; char a,b; bool flag; int main() { while(scanf("%d%d ",&n,&m) != EOF && n) { pos = 0; memset(d,0,sizeof(d)); for (i = 1; i <= n; i++) d[i][i] = 1; for (i = 1; i <= m; i++) { scanf("%c<%c ",&a,&b); d[a - 'A' + 1][b - 'A' + 1] = 1; for (j = 1; j <= n; j++) { for (k = 1; k <= n; k++) { d[j][k] |= d[j][a - 'A' + 1] & d[b - 'A' + 1][k]; } } flag = true; for (j = 1; j <= n; j++) { for (k = j + 1; k <= n; k++) { if (d[j][k] && d[k][j]) { if (!pos) pos = i; break; } if (!d[j][k] && !d[k][j]) { flag = false; break; } } if (pos) break; } if (flag && !pos) { printf("Sorted sequence determined after %d relations: ",i); memset(cnt,0,sizeof(cnt)); for (j = 1; j <= n; j++) { for (k = 1; k <= n; k++) { if (j != k) cnt[j] += d[j][k]; } } for (j = n - 1; j >= 0; j--) { for (k = 1; k <= n; k++) { if (cnt[k] == j) printf("%c",k + 'A' - 1); } } printf(". "); i++; for (i; i <= m; i++) scanf("%c<%c ",&a,&b); break; } } if (flag && !pos) continue; else if (pos) printf("Inconsistency found after %d relations. ",pos); else printf("Sorted sequence cannot be determined. "); } return 0; }