zoukankan      html  css  js  c++  java
  • POJ 3177 Redundant Paths (tarjan无向图求缩点)

    #include <iostream>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    #include<vector>
    #include<cstdio>
    #include<stack>
    #include <map>
    #define lson(p) (p<<1)
    #define rson(p) (p<<1|1)
    #define ll long long
    using namespace std;
    const int N = 1e5+10;
    int n,m;
    struct Edge{
        int to,nxt;
    }edge[N<<2];
    int tot,head[N];
    int dfn[N],low[N],fa[N],d[N];
    stack<int> st;
    int ind,ans;
    void init(){
        tot = 0;
        memset(head,-1,sizeof head);
        memset(dfn,0,sizeof dfn);
        memset(low,0,sizeof low);
    }
    void add(int u,int v){
        edge[tot].to = v;
        edge[tot].nxt = head[u];
        head[u] = tot++;
    }
    void tarjan(int u,int root){
        int v,sg=0;
        dfn[u] = low[u] = ++ind;
        st.push(u);
        for(int i =head[u];i!=-1;i=edge[i].nxt){
            v = edge[i].to;
            if(v==root && !sg) {
                sg = 1;
                continue;
            }
            if(!dfn[v]){
                tarjan(v,u);
                low[u] = min(low[u],low[v]);
            }
            else if(dfn[v] < dfn[u]){
                low[u] = min(low[u],dfn[v]);
            }
        }
        if(low[u]== dfn[u]){
            int v = st.top();
            while(v !=u){
                fa[v] = u;
                st.pop();
                v = st.top();
            }
            fa[u] = u;
            st.pop();
        }
    }
    void solve(){
        int fr,to;
        init();
        for(int i=1;i<=m;++i){
            scanf("%d%d",&fr,&to);
            add(fr,to);
            add(to,fr);
        }
        tarjan(1,0);
        for(int i=1;i<=n;++i){
            for(int j=head[i];j!=-1;j=edge[j].nxt){
                if(fa[i]!=fa[edge[j].to]){
                    d[fa[i]]++;
                    d[fa[edge[j].to]]++;
                }
            }
        }
        int cnt = 1;
        for(int i=1;i<=n;++i){
            if(d[i]==2){
                cnt++;
            }
        }
        printf("%d
    ",(cnt)/2);
    }
    int main()
    {
        while(scanf("%d%d",&n,&m)){
            solve();
            break;
        }
        return 0;
    }
    
    
  • 相关阅读:
    codeforces 189A
    hdu 2085
    hdu 2083
    cf 1237 C2. Balanced Removals (Harder)
    cf 1244 D. Paint the Tree
    cf 1241 E. Paint the Tree(DP)
    cf 1241 D. Sequence Sorting(思维)
    cf1228 D Complete Tripartite(哈希)
    Windows10 与 WSL(Ubuntu)的文件互访
    Ubuntu下运行python文件
  • 原文地址:https://www.cnblogs.com/xxrlz/p/11368106.html
Copyright © 2011-2022 走看看