题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1269
题意:问当前图是不是强连通的
代码:
#include <bits/stdc++.h>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 10000 + 50;
int top[maxn],id[maxn],inStack[maxn],TOT;
stack<int> ST;
vector<int> Adj[maxn];
int n,m;
bool DFS(int u){
id[u] = top[u] = TOT++;
inStack[u] = 1;
ST.push(u);
int len = Adj[u].size(),v;
for(int i = 0;i < len;++i){
v = Adj[u][i];
if(id[v] == -1){
if(!DFS(v)) return false;
top[u] = min(top[u],top[v]);
}else if(inStack[v])
top[u] = min(top[u],id[v]);
}
int ret = 0;
if(id[u] == top[u]){
while(ST.top() != u){
ret++;ST.pop();
}ST.pop();ret++;
return ret == n;
}
return true;
}
char ans[][10] = {"No","Yes"};
int main(){
while( ~sf("%d %d",&n,&m) && (n || m) ){
while(ST.size()) ST.pop();
for(int i = 1;i <= n;++i) Adj[i].clear();
memset(id,-1,sizeof id);TOT = 1;
for(int i = 0;i < m;++i){
int u,v;sf("%d %d",&u,&v);
Adj[u].push_back(v);
}
pf("%s\n",ans[DFS(1)]);
}
}