【模板】【hdu1269】迷宫城堡——tarjan

题目链接

判断一个图是否为强联通图,只要tarjan求出强联通分量的个数,若个数大于1则不是连通图,tarjan的模板题。

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<cstring>
 4 #include<algorithm>
 5 #define mem(a) memset(a,0,sizeof(a))
 6 typedef long long LL;
 7 const int maxn=1e5+5;
 8 using namespace std;
 9 int n,m,tot=0,sum=0,first[maxn],low[maxn],Dfn[maxn],tail=0,cnt=0;
10 bool ok[maxn];
11 int st[maxn];
12 struct node{
13     int next,to;
14 }e[maxn];
15 inline int read()
16 {
17     int ans=0,f=1;char c=getchar();
18     while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
19     while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();}
20     return ans*f;
21 }
22 /*----------------------------------------------------------*/
23 inline void add(int u,int v)
24 {
25     tot++;e[tot].next=first[u];first[u]=tot;e[tot].to=v;
26 }
27 void tarjan(int x)
28 {
29     ok[x]=1;
30     low[x]=Dfn[x]=++sum;
31     st[++tail]=x;
32     for(int i=first[x];i;i=e[i].next){
33         int to=e[i].to;
34         if(!Dfn[to]){
35             tarjan(to);
36             if(low[to]<low[x])low[x]=low[to];
37         }
38         else if(ok[to]&&Dfn[to]<low[x])low[x]=Dfn[to];
39     }
40     if(Dfn[x]==low[x]){
41         int p;
42         cnt++;
43         do{
44             p=st[tail];
45             ok[p]=0;
46             tail--;
47         }while(p!=x);
48     }
49 }
50 int main()
51 {
52     n=read();m=read();
53     int a,b;
54     while(n||m){
55         mem(first);
56         mem(Dfn);
57         mem(low);
58         mem(ok);
59         tail=0;sum=0;tot=0;cnt=0;
60         for(int i=1;i<=m;i++){
61             a=read();b=read();
62             add(a,b);
63         }
64         for(int i=1;i<=n;i++)
65             if(!Dfn[i])tarjan(i);
66         if(cnt==1)printf("Yes
");
67         else printf("No
");
68         n=read();m=read();
69     }
70     return 0;
71 }
hdu1269
原文地址:https://www.cnblogs.com/JKAI/p/7454834.html