题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1003
拓扑排序判圈 ,若存在元素不在拓扑序中,则存在圈。
代码:
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <sstream>
#include <malloc.h>
#include <functional>
using namespace std;
char a[15], b[15];
map<string, int> mp;
int m, n, in[10010], tot;
struct Edge
{
int to, next;
}edge[10010];
int head[10010];
void addedge(int u, int v)
{
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void init()
{
tot = 0;
memset(head, -1, sizeof(head));
memset(in, 0, sizeof(in));
mp.clear();
n = 0;
}
int main()
{
int t, cases = 1;
scanf("%d", &t);
while (t--)
{
scanf("%d", &m);
init();
for (int i = 1;i <= m;i++)
{
scanf("%s %s", a, b);
if (mp.find(a) == mp.end()) mp[a] = ++n;
if (mp.find(b) == mp.end()) mp[b] = ++n;
in[mp[b]]++;
addedge(mp[a], mp[b]);
}
int cnt = n;
queue<int> que; while (!que.empty()) que.pop();
for (int i = 1;i <= n;i++) if (in[i] == 0) que.push(i);
while (!que.empty())
{
int tmp = que.front();que.pop();
cnt--;
for (int i = head[tmp];i != -1;i = edge[i].next)
{
int v = edge[i].to;
in[v]--;
if (in[v] == 0) que.push(v);
}
}
if (!cnt) printf("Case %d: Yes\n", cases++);
else printf("Case %d: No\n", cases++);
}
return 0;
}