题目链接:点击查看
题目大意:给出一张 n 个点 m 条边的有向图,问对于任意不相等的 a 和 b ,是否满足存在 a 到 b 的一条路径或者 b 到 a 的一条路径
题目分析:判断是否存在路径的话,对于一个环来说,显然环中的任意两个节点互相都是可达的,所以对题目不具有贡献,我们可以先用 tarjan 缩一下点,这样就可以在新图上拓扑了,对于新图来说拓扑序必须唯一才能满足题意,否则的话肯定会存在着两个点 a 和 b 不满足题意
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=2e3+100;
const int M=1e4+100;
struct Egde
{
int to,next;
}edge1[M],edge2[M];
int head1[N],head2[N],low[N],dfn[N],c[N],Stack[N],num,cnt,cnt2,cnt1,dcc,n,m,top,in[N];
bool ins[N];
vector<int>scc[N];
void addedge1(int u,int v)
{
edge1[cnt1].to=v;
edge1[cnt1].next=head1[u];
head1[u]=cnt1++;
}
void addedge2(int u,int v)
{
edge2[cnt2].to=v;
edge2[cnt2].next=head2[u];
head2[u]=cnt2++;
}
void tarjan(int u)
{
dfn[u]=low[u]=++num;
Stack[++top]=u;
ins[u]=true;
for(int i=head1[u];i!=-1;i=edge1[i].next)
{
int v=edge1[i].to;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(ins[v])
low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
cnt++;
int v;
do
{
v=Stack[top--];
ins[v]=false;
c[v]=cnt;
scc[cnt].push_back(v);
}while(u!=v);
}
}
void solve()
{
for(int i=1;i<=n;i++)//缩点
if(!dfn[i])
tarjan(i);
}
void build()//缩点+连边
{
solve();
for(int i=1;i<=n;i++)
{
for(int j=head1[i];j!=-1;j=edge1[j].next)
{
int u=i;
int v=edge1[j].to;
if(c[u]!=c[v])
{
addedge2(c[u],c[v]);
in[c[v]]++;
}
}
}
}
bool topo()
{
queue<int>q;
for(int i=1;i<=cnt;i++)
if(!in[i])
q.push(i);
if(q.size()>1)
return false;
while(q.size())
{
int u=q.front();
q.pop();
int tot=0;
for(int j=head2[u];j!=-1;j=edge2[j].next)
{
int v=edge2[j].to;
if(--in[v]==0)
{
tot++;
q.push(v);
}
}
if(tot>1)
return false;
}
return true;
}
void init()
{
for(int i=0;i<N;i++)
scc[i].clear();
top=cnt=cnt1=cnt2=num=dcc=0;
memset(head2,-1,sizeof(head2));
memset(head1,-1,sizeof(head1));
memset(low,0,sizeof(low));
memset(dfn,0,sizeof(dfn));
memset(c,0,sizeof(c));
memset(ins,false,sizeof(ins));
memset(in,0,sizeof(in));
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int w;
cin>>w;
int kase=0;
while(w--)
{
init();
scanf("%d%d",&n,&m);
while(m--)
{
int u,v;
scanf("%d%d",&u,&v);
addedge1(u,v);
}
build();
if(topo())
printf("Case %d: Kalimdor is just ahead\n",++kase);
else
printf("Case %d: The Burning Shadow consume us all\n",++kase);
}
return 0;
}