题目大意:问所给的边中,有没有出现环
解题思路:拓扑排序判环了
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <queue>
using namespace std;
const int N = 10010;
struct Edge{
int u, v, next;
Edge() {}
Edge(int u, int v, int next): u(u), v(v), next(next) {}
}E[N];
map<string, int> Map;
int m, n, cas = 1;
int in[2 * N], head[N * 2];
void init() {
cin >> m;
Map.clear();
memset(in, 0, sizeof(in));
memset(head, -1, sizeof(head));
n = 0;
string a, b;
for (int i = 0; i < m; i++) {
cin >> a >> b;
if (!Map[a]) Map[a] = ++n;
if (!Map[b]) Map[b] = ++n;
in[Map[b]]++;
E[i] = Edge(Map[a], Map[b], head[Map[a]]);
head[Map[a]] = i;
}
}
void solve() {
queue<int> Q;
for (int i = 1; i <= n; i++)
if (!in[i]) Q.push(i);
int cnt = 0;
while (!Q.empty()) {
int u = Q.front(); Q.pop();
cnt++;
for (int i = head[u]; ~i; i = E[i].next) {
int v = E[i].v;
in[v]--;
if (!in[v]) Q.push(v);
}
}
if (cnt == n) printf("Case %d: Yes\n", cas++);
else printf("Case %d: No\n", cas++);
}
int main() {
int test;
cin >> test;
while (test--) {
init();
solve();
}
return 0;
}