51nod 1076强连通

Tarjan算法来解这题。无向图可以转化为有向图来解决。

#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define INF 1000000001
#define ll __int64
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int MAXN = 25010;
struct node
{
    int to;
    int next;
}edge[MAXN*5];
stack<int>s;
int n,m,pre[MAXN],ind,low[MAXN],dfn[MAXN],vis[MAXN],pa[MAXN],ins[MAXN];
void add(int x,int y)
{
    edge[ind].to = y;
    edge[ind].next = pre[x];
    pre[x] = ind ++;
}
int find(int x)
{
    if(x != pa[x])pa[x] = find(pa[x]);
    return pa[x];
}
void dfs(int rt,int k,int fa)
{
    ins[rt] = 1;
    vis[rt] = 1;
    low[rt] = dfn[rt] = k;
    s.push(rt);
    for(int i = pre[rt]; i!=-1; i=edge[i].next){
        int t = edge[i].to;
        if(!dfn[t] && t != fa){
            dfs(t,k+1,rt);
            low[rt] = min(low[t],low[rt]);
        }
        else if(ins[rt] && t != fa){
            low[rt] = min(dfn[t],low[rt]);
        }
    }
    if(low[rt] == dfn[rt]){
        while(!s.empty()){
            int temp = s.top();
            s.pop();
            int fx = find(temp);
            int fy = find(rt);
            if(fx != fy){
                pa[fx] = fy;
            }
            if(temp == rt)break;
        }
    }
}
int main()
{
    while(cin >>n >>m){
        ind = 1;
        for(int i = 1; i <= n; i++)pa[i] = i;
        memset(ins,0,sizeof(ins));
        memset(low,0,sizeof(low));
        memset(dfn,0,sizeof(dfn));
        memset(pre,-1,sizeof(pre));
        memset(vis,0,sizeof(vis));
        for(int i = 1; i <= m; i++){
            int x,y;
            cin >>x >>y;
            add(x,y);
            add(y,x);
        }

        for(int i = 1; i<= n; i++){
            if(!vis[i]){
                dfs(i,1,-1);
            }
        }

        int q;
        cin >>q;

        while(q--){
            int x,y;
            cin >>x >>y;
            if(find(x) == find(y)){
                cout<<"Yes"<<endl;
            }
            else {
                cout<<"No"<<endl;
            }
        }
    }
    return 0;
}

 

posted @ 2016-03-29 20:06  sweat123  阅读(177)  评论(0编辑  收藏  举报