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
【分析】
tarjan+topsort判断是否连通
其实我感觉是求整个缩点后的图是否是一条链…233
【代码】
//poj 2762 Going from u to v or from v to u?
#include<stack>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=1005;
vector <int> f[mxn];
stack <int> s;
int n,m,tim,cnt,num,T;
int dfn[mxn],low[mxn],be[mxn],from[6005],to[6005],ru[mxn];
bool in[mxn],vis[mxn];
inline void tarjan(int u)
{
int i,j,v;
dfn[u]=low[u]=++tim;
s.push(u),in[u]=1;
for(i=0;i<f[u].size();i++)
{
v=f[u][i];
if(!dfn[v]) tarjan(v),low[u]=min(low[u],low[v]);
else if(in[v]) low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
num++;
do
{
v=s.top();
s.pop();
in[v]=0;
be[v]=num;
}while(u!=v);
}
}
inline bool topsort()
{
int i,j,u,v,cnt=0;
queue <int> q;
fo(i,1,num) if(!ru[i]) q.push(i),cnt++;
if(cnt>1) return 0;
while(!q.empty())
{
u=q.front();
q.pop();
cnt=0;
for(i=0;i<f[u].size();i++)
{
v=f[u][i];
ru[v]--;
if(!ru[v]) q.push(v),cnt++;
}
if(cnt>1) return 0;
}
return 1;
}
int main()
{
int i,j,u,v;
scanf("%d",&T);
while(T--)
{
int flag=0;
num=0;M(dfn);M(low);M(vis);M(in);M(be);M(ru);
while(!s.empty()) s.pop();
scanf("%d%d",&n,&m);
fo(i,1,n) f[i].clear();
fo(i,1,m)
{
scanf("%d%d",&from[i],&to[i]);
f[from[i]].push_back(to[i]);
}
fo(i,1,n) if(!dfn[i]) tarjan(i);
fo(i,1,n) f[i].clear();
fo(i,1,m)
{
u=from[i],v=to[i];
if(be[u]!=be[v])
f[be[u]].push_back(be[v]),ru[be[v]]++;
}
if(!topsort()) printf("No\n");
else printf("Yes\n");
}
return 0;
}