题意:给你一个有向图,输出其中的最小环
解题思路:数据只有500,暴力即可
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
map<string,int> mp;
char ch[100010], name[505][10], s[20];
int f[505],nt[250009],e[250009];
int n,cnt,x;
int p[510],dis[510];
int bfs(int root)
{
memset(dis, INF, sizeof dis);
bool flag = true;
queue<int> q;
q.push(root);
while(!q.empty())
{
int pre = q.front();
q.pop();
if(pre==root)
{
if(!flag) return dis[root];
else flag = false;
}
for(int i=f[pre]; ~i; i=nt[i])
{
int temp;
if(pre==root) temp = 1;
else temp = dis[pre] + 1;
if(dis[e[i]] > temp)
{
q.push(e[i]);
dis[e[i]] = temp;
}
}
}
return INF;
}
int main()
{
while(~scanf("%d",&n))
{
cnt=0;
memset(f,-1,sizeof f);
mp.clear();
for(int i=1; i<=n; i++)
{
scanf("%s",name[i]);
mp[name[i]] = i;
}
for(int i=1; i<=n; i++)
{
scanf("%s%d",name[i],&x);
for(int j=1; j<=x; j++)
{
scanf("%s",ch);
getchar();
gets(ch);
int tot = 0;
int len = strlen(ch);
for(int k=0; k<len; k++)
{
if(ch[k] == ',')
{
s[tot] = '\0';
nt[cnt]=f[mp[s]],f[mp[s]]=cnt,e[cnt++]=i;
k++;
tot=0;
}
else s[tot++]=ch[k];
}
s[tot]='\0';
nt[cnt]=f[mp[s]],f[mp[s]]=cnt,e[cnt++]=i;
}
}
int pos = -1, mi = INF;
for(int i=1; i<=n;i++)
{
int temp = bfs(i);
if(temp < mi)
{
mi = temp;
pos = i;
}
}
if(mi == INF)
{
printf("SHIP IT\n");
continue;
}
queue<int> q;
q.push(pos);
memset(dis, INF, sizeof dis);
while(!q.empty())
{
int pre = q.front();
q.pop();
int flag=0;
for(int i=f[pre]; ~i; i=nt[i])
{
int temp;
if(pre == pos) temp = 1;
else temp = dis[pre] + 1;
if(dis[e[i]] > temp)
{
p[e[i]] = pre;
q.push(e[i]);
dis[e[i]] = temp;
}
if(e[i] == pos)
{
p[pos] = pre;
flag=1;
break;
}
}
if(flag) break;
}
int temp = pos;
while(p[temp] != pos)
{
printf("%s ",name[p[temp]]);
temp = p[temp];
}
printf("%s\n",name[pos]);
}
return 0;
}