像拓扑排序那样先搞好。然后只要判断一下这张图中入度为0的节点有几个,如果有1个就输出yes。0个或者1个以上的全部输出no。
#include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<map> #include<string> #include<algorithm> using namespace std; int rudu[2005]; vector<int>abc[2005]; map<string, int>dd; int main() { int n, m, i, x, y, j, k, ji; while (~scanf("%d", &m)) { if (m == 0) break; n = 1; memset(rudu, 0, sizeof(rudu)); for (i = 0; i < 2004; i++) abc[i].clear(); dd.clear(); char s1[1000], s2[1000]; for (i = 0; i < m; i++) { scanf("%s%s", s1, s2); if (dd[s1] == 0){ dd[s1] = n; n++; } if (dd[s2] == 0){ dd[s2] = n; n++; } x = dd[s1]; y = dd[s2]; rudu[y]++; abc[x].push_back(y); } int sum = 0; for (i = 1; i <=1; i++) { sum = 0; for (j = 1; j <= n-1; j++) { if (rudu[j] == 0) { sum++; ji = j; } } if (sum > 1||sum==0) break; else { rudu[ji]--; for (k = 0; k < abc[ji].size(); k++) rudu[abc[ji][k]]--; } } if (i == 2) printf("Yes "); else printf("No "); } return 0; }