标签:hdu1269
题意:判定给出的有向图是不是强连通图
Tarjan算法模板题目
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define fread(zcc) freopen(zcc,"r",stdin)
#define fwrite(zcc) freopen(zcc,"w",stdout)
using namespace std;
const int maxn=100005;
const int inf=999999;
vector<int> G[maxn];
int dfn[maxn],low[maxn],s[maxn];//依次对应,访问的序号,能到达的最早的,栈
int belong[maxn];//连通分量的编号
bool ins[maxn];//是否在栈里
int cnt,num,top;//连通分量的编号,访问的序号,栈的指针
void dfs(int u){
dfn[u]=low[u]=++num;
s[++top]=u;
ins[u]=true;
int N=G[u].size();
for(int i=0;i<N;i++){
int v=G[u][i];
if(!dfn[v]){
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(ins[v]&&dfn[v]<low[u]){
low[u]=dfn[v];
}
}
if(low[u]==dfn[u]){
cnt++;
int v;
do{
v=s[top--];
ins[v]=false;
belong[v]=cnt;
}while(v!=u);
}
}
void Tarjan(int n){
cnt=num=top=0;
cl(dfn,0);
cl(ins,false);
cl(belong,0);
for(int i=1;i<=n;i++)if(!dfn[i]){
dfs(i);
}
}
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)&&(n||m)){
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
G[a].pb(b);
}
Tarjan(n);
for(int i=1;i<=n;i++){
if(belong[i]!=cnt){
puts("No");goto A;
}
}
puts("Yes");
A:;
for(int i=0;i<=n;i++)G[i].clear();
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:hdu1269
原文地址:http://blog.csdn.net/u013167299/article/details/48008355