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
先强连通缩点,再用拓扑排序,如果入度为0的点大于1个,就直接返回输出no,如果入度为0的点不超过2个输出yes
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#define maxn 1005
#define maxm 6005
using namespace std;
int low[maxn];
int dfn[maxn];
int head[maxn];
int sccno[maxn];
int dfsclock;
int sccnt;
int n,m,nm;
int in[maxn];
int cnt;
int t;
int u,v;
stack<int>s;
vector<int>g[maxn];
void init()
{
memset(head,-1,sizeof(head));
cnt=0;
}
struct edge
{
int v,next;
}edges[maxm];
void addedge(int u,int v)
{
edges[cnt].next=head[u];
edges[cnt].v=v;
head[u]=cnt++;
}
void dfs(int u)
{
low[u]=dfn[u]=++dfsclock;
s.push(u);
for(int i=head[u];i!=-1;i=edges[i].next)
{
int v=edges[i].v;
if(!dfn[v])
{
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(!sccno[v])
{
low[u]=min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u])
{
sccnt++;
while(true)
{
int x=s.top();
s.pop();
sccno[x]=sccnt;
if(x==u)
break;
}
}
}
void findscc(int n)
{
dfsclock=sccnt=0;
memset(sccno,0,sizeof(sccno));
memset(dfn,0,sizeof(dfn));
for(int i=1;i<=n;i++)
if(!dfn[i])
dfs(i);
}
void top()
{
queue<int>q;
int sum=0;
for(int i=1;i<=sccnt;i++)
{if(in[i]==0)
{sum++;
q.push(i);
}
if(sum>1)
{
printf("No\n");
return ;
}
}
while(!q.empty())
{
int u=q.front();
q.pop();
sum=0;
for(int i=0;i<g[u].size();i++)
{
int v=g[u][i];
if(--in[v]==0)
{
sum++;
if(sum>1)
{
printf("No\n");
return;
}
q.push(v);
}
}
}
printf("Yes\n");
}
int main()
{
scanf("%d",&t);
while(t--)
{init();
scanf("%d%d",&n,&m);
while(m--)
{
int u,v;
scanf("%d%d",&u,&v);
addedge(u,v);
}
findscc(n);
for(int i=1;i<=sccnt;i++)
{g[i].clear();
in[i]=0;
}
for(int u=1;u<=n;u++)
for(int i=head[u];i!=-1;i=edges[i].next)
{
int v=edges[i].v;
if(sccno[u]!=sccno[v])
{
in[sccno[v]]++;
g[sccno[u]].push_back(sccno[v]);
}
}
top();
}
return 0;
}