n点m边
求是否能从任意a->b b->a
强连通分量等于1
1 #include<stdio.h> 2 #include<algorithm> 3 #include<string.h> 4 #include<queue> 5 #include<math.h> 6 #include<stack> 7 8 using namespace std; 9 10 #define MAXN 100010 11 12 int head[MAXN],low[MAXN],dfn[MAXN],f[MAXN]; 13 bool vis[MAXN]; 14 int cnt,k,num; 15 struct edg 16 { 17 int fr,to,next; 18 19 }x[MAXN]; 20 21 void add(int u,int v) 22 { 23 x[cnt].next=head[u]; 24 x[cnt].fr=u; 25 x[cnt].to=v; 26 head[u]=cnt++; 27 } 28 stack<int>s; 29 30 void dfs(int u) 31 { 32 low[u]=dfn[u]=k++; 33 vis[u]=1; 34 s.push(u); 35 int i; 36 for(i=head[u];i!=-1;i=x[i].next) 37 { 38 int t=x[i].to; 39 if(!dfn[t]) 40 { 41 dfs(t); 42 low[u]=min(low[u],low[t]); 43 } 44 else if(vis[t]) 45 low[u]=min(low[u],dfn[t]); 46 } 47 if(low[u]==dfn[u]) 48 { 49 num++; 50 while(!s.empty()) 51 { 52 int now=s.top(); 53 s.pop(); 54 vis[now]=0; 55 f[now]=num; 56 if(now==u)break; 57 } 58 } 59 } 60 int main() 61 { 62 int n,m; 63 64 while(scanf("%d%d",&n,&m)!=EOF) 65 { 66 if(n+m==0) 67 break; 68 int i; 69 memset(head,-1,sizeof(head)); 70 cnt=0; 71 for(i=1;i<=m;i++) 72 { 73 int a,b; 74 scanf("%d%d",&a,&b); 75 add(a,b); 76 } 77 k=1; 78 num=0; 79 memset(dfn,0,sizeof(dfn)); 80 memset(low,0,sizeof(low)); 81 memset(vis,0,sizeof(vis)); 82 memset(f,0,sizeof(f)); 83 for(i=1;i<=n;i++) 84 { 85 if(!dfn[i]) 86 dfs(i); 87 } 88 if(num==1) 89 printf("Yes\n"); 90 else 91 printf("No\n"); 92 } 93 return 0; 94 }
时间: 2024-10-03 21:41:31