# POJ2762 Going from u to v or from v to u?（强连通缩点+拓扑排序）

Going from u to v or from v to u?
 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 15196 Accepted: 4013

Description

In order to make their sons brave, Jiajia and Wind take them to a big cave. The cave has n rooms, and one-way corridors connecting some rooms. Each time, Wind choose two rooms x and y, and ask one of their little sons go from one to the other. The son can either go from x to y, or from y to x. Wind promised that her tasks are all possible, but she actually doesn't know how to decide if a task is possible. To make her life easier, Jiajia decided to choose a cave in which every pair of rooms is a possible task. Given a cave, can you tell Jiajia whether Wind can randomly choose two rooms without worrying about anything?

Input

The first line contains a single integer T, the number of test cases. And followed T cases.

The first line for each case contains two integers n, m(0 < n < 1001,m < 6000), the number of rooms and corridors in the cave. The next m lines each contains two integers u and v, indicating that there is a corridor connecting room u and room v directly.

Output

The output should contain T lines. Write 'Yes' if the cave has the property stated above, or 'No' otherwise.

Sample Input

1
3 3
1 2
2 3
3 1


Sample Output

Yes

Source

#include<stdio.h>
#include<vector>
#include<string.h>
using namespace std;
const int N = 1005;

int dfn[N],low[N],Stack[N],indx[N],vist[N],top,deep,k,tt;
vector<int>mapt[N];
void dfs(int u)
{
deep++;
vist[u]=tt;
Stack[++top]=u;
dfn[u]=low[u]=deep;
int len=mapt[u].size();
for(int i=0;i<len;i++)
{
int v=mapt[u][i];
if(vist[v]==0)
{
dfs(v);
if(low[u]>low[v])
low[u]=low[v];
}
else if(vist[v]==tt&&low[u]>dfn[v])//有向图一定要用vist[v]==tt
low[u]=dfn[v];
}
if(dfn[u]==low[u])
{
k++;
while(u!=Stack[top])
indx[Stack[top--]]=k;
indx[Stack[top--]]=k;
}
}
int in[N],mapt1[N][N];
int tope()
{
int a[N],m=0;
for(int i=1;i<=k;i++)
if(in[i]==0)
a[m++]=i;
while(m--)
{
if(m)
return 0;
int s=a[m];
for(int i=1;i<=k;i++)
if(mapt1[s][i])
{
in[i]-=mapt1[s][i];
if(in[i]==0)
a[m++];
}
}
return 1;
}
int main()
{
int t,n,m,a,b;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
vist[i]=in[i]=0;  mapt[i].clear();
}
memset(mapt1,0,sizeof(mapt1));
top=k=deep=tt=0;

while(m--)
{
scanf("%d%d",&a,&b);
mapt[a].push_back(b);
}

for(int i=1;i<=n;i++)
if(vist[i]==0)
{
tt++;
dfs(i);
}
for(int i=1;i<=n;i++)
{
int u=indx[i];
for(int j=0;j<mapt[i].size();j++)
{
int v=indx[mapt[i][j]];
if(u==v)
continue;
mapt1[u][v]++; in[v]++;
}
}

int flag=tope();
if(flag==1)
printf("Yes\n");
else printf("No\n");
}
}


• 评论

• 上一篇
• 下一篇