poj2762
题解:只要缩点后的DAG是一条链就可以实现任意两个room之间存在一条单向路
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<algorithm>
#include<string>
#include<stack>
#include<map>
#include<cmath>
#include<queue>
#include<set>
#include<string>
using namespace std;
typedef pair<int,int> P;
typedef long long LL;
typedef unsigned long long ULL;
const LL mod=1e9+7;
const LL LL_MAX=9223372036854775807;
const int maxn=1000+10;
LL read()
{
LL x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int read1()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
vector<int> G[maxn],g[maxn];
int dfn[maxn],low[maxn],cnt;
stack<int> st;
int ins[maxn];
int n,m;
int scc,bcc[maxn],in[maxn];
void init()
{
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(bcc,0,sizeof(bcc));
memset(in,0,sizeof(in));
scc=0;
cnt=0;
for(int i=0;i<=n;i++){
G[i].clear();
g[i].clear();
}
while(!st.empty()){
st.pop();
}
memset(ins,0,sizeof(ins));
}
void tarjan(int u)
{
dfn[u]=low[u]=++cnt;
st.push(u);
ins[u]=1;
int len=G[u].size();
for(int i=0;i<len;i++){
int v=G[u][i];
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]){
++scc;
while(1){
int pre=st.top();
st.pop();
ins[pre]=0;
bcc[pre]=scc;
if(pre==u)break;
}
}
}
int dep;
void dfs(int u,int step)
{
dep=max(dep,step);
for(int i=0;i<g[u].size();i++){
int v=g[u][i];
dfs(v,step+1);
}
}
int main()
{
int t;
cin>>t;
while(t--){
scanf("%d%d",&n,&m);
init();
for(int i=1;i<=m;i++){
int s,e;
s=read1();e=read1();
G[s].push_back(e);
}
for(int i=1;i<=n;i++){
if(!dfn[i]){
tarjan(i);
}
}
for(int i=1;i<=n;i++){
for(int j=0;j<G[i].size();j++){
int s=i,e=G[i][j];
if(bcc[s]!=bcc[e]){
g[bcc[s]].push_back(bcc[e]);
in[bcc[e]]++;
}
}
}
int st;
for(int i=1;i<=scc;i++){
if(in[i]==0){
st=i;
break;
}
}
dep=0;
dfs(st,1);
if(dep==scc){
printf("Yes\n");
}
else{
printf("No\n");
}
}
return 0;
}