思路: 拓扑排序, 判断是否有环;
#includeusing namespace std;const int maxn = 1e4 + 131;struct Node{ int nxt, to;}edge[maxn];int Head[maxn], tot;void AddEdge(int From, int To){ edge[tot].to = To; edge[tot].nxt = Head[From]; Head[From] = tot++;}map StoI;string a, b;int Vis[maxn];/// 记录节点的访问次数void TopSort(int n){ queue qu; int lest = n; for(int i = 1; i <= n; ++i) { if(!Vis[i]) qu.push(i); } while(!qu.empty()) { int u = qu.front(); qu.pop(); --lest; for(int i = Head[u]; i != -1; i = edge[i].nxt) { int v = edge[i].to; --Vis[v]; if(!Vis[v]) qu.push(v); } } if(lest) puts("No"); else puts("Yes");}int main(){ int t; scanf("%d",&t); for(int kase = 1; kase <= t; ++kase) { int m; scanf("%d",&m); StoI.clear(); memset(Head,-1,sizeof(Head)); tot = 0; int n = 0; memset(Vis, 0, sizeof(Vis)); for(int i = 1; i <= m; ++i) { cin >> a >> b; if(StoI.find(a) == StoI.end()) StoI[a] = ++n; if(StoI.find(b) == StoI.end()) StoI[b] = ++n; ++Vis[StoI[b]]; AddEdge(StoI[a], StoI[b]); } printf("Case %d: ",kase); TopSort(n); } return 0;}