思路:强连通,将他变成有向图,并且不能返回父节点
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=30000; 4 5 struct node{ 6 int v,next; 7 }edg[50004*3]; 8 int head[maxn],tot=0; 9 void add(int u,int v){ 10 edg[tot].v=v;edg[tot].next=head[u];head[u]=tot++; 11 } 12 int dfn[maxn],low[maxn],belong[maxn]; 13 bool instack[maxn]; 14 int Stack[maxn],index,top,bcnt; 15 set<int >s[maxn]; 16 void dfs(int u,int fa) 17 { 18 dfn[u]=low[u]=++index; 19 Stack[++top]=u; 20 instack[u]=true; 21 for(int i=head[u];i!=-1;i=edg[i].next) 22 { 23 int v=edg[i].v; 24 if(!dfn[v]){ 25 dfs(v,u); 26 low[u]=min(low[u],low[v]); 27 }else if(instack[v]&&v!=fa) low[u]=min(low[u],dfn[v]); 28 } 29 int v; 30 if(dfn[u]==low[u]){ 31 bcnt++; 32 do{ 33 v=Stack[top--]; 34 instack[v]=false; 35 belong[v]=bcnt; 36 // s[bcnt].insert(v); 37 }while(u!=v); 38 } 39 } 40 int n,m; 41 void Tarjan() 42 { 43 memset(dfn,0,sizeof(dfn)); 44 bcnt = top = index = 0; 45 for(int i=1;i<=n;i++) 46 if(!dfn[i]) 47 dfs(i,-1); 48 } 49 50 int main(){ 51 int x,y; 52 memset(head,-1,sizeof(head)); 53 scanf("%d%d",&n,&m); 54 for(int i=1;i<=m;i++){ 55 scanf("%d%d",&x,&y); 56 add(x,y);add(y,x); 57 } 58 Tarjan(); 59 //for(int i=1;i<=n;i++) cout<<belong[i]<<endl; 60 int q; 61 scanf("%d",&q); 62 while(q--){ 63 scanf("%d%d",&x,&y); 64 // cout<<belong[x]<<" "<<belong[y]<<" "<<s[belong[x]].size()<<endl; 65 if(belong[x]==belong[y]){ 66 cout<<"Yes"<<endl; 67 } 68 else cout<<"No"<<endl; 69 } 70 return 0; 71 }
时间: 2024-10-28 10:04:31