• 并查集 带压缩路径的版本


    #include <iostream>
    using namespace std;
     
    typedef struct
    {
        int a,b;
    }road;
     
    const int MAX=5001;
    int N,M,K;
    int father[MAX];
    int rank[MAX];
    road rd[500000];
     
    void make_set()
    {
        int i;
        for(i=1;i<=N;i++)
        {
            father[i]=i;
            rank[i]=0;
        }
    }
     
    int find_set(int x)
    {
        if(x!=father[x])
            father[x]=find_set(father[x]);
        return father[x];
    }
     
    void union_set(int x,int y)
    {
        x=find_set(x);
        y=find_set(y);
        if(x==y)
            return ;
        if(rank[x]>rank[y])
            father[y]=x;
        else
        {
            father[x]=y;
            if(rank[x]==rank[y])
                rank[y]++;
        }
    }
     
    int main()
    {
        cin>>N>>M>>K;
        int i,j;
        int start,end;
        int input;
        for(i=1;i<=M;i++)
        {
            cin>>start>>end;
            rd[i].a=start;
            rd[i].b=end;
        }
        for(i=1;i<=K;i++)
        {
            int cnt=-2;
            cin>>input;
            make_set();
            for(j=1;j<=M;j++)
            {
                if(rd[j].a!=input && rd[j].b!=input)
                    union_set(rd[j].a,rd[j].b);
            }
            for(j=1;j<=N;j++)
            {
                if(father[j]==j)
                    cnt++;
            }
            cout<<cnt<<endl;
        }
        return 0;
    }
    /**************************************************************
        Problem: 1325
        User: feng345feng
        Language: C++
        Result: Accepted
        Time:800 ms
        Memory:5456 kb
    ****************************************************************/
  • 相关阅读:
    工具 Dotnet IL Editor 推荐
    VC6.0开发OCX按钮控件
    变量共享分析(Thread)
    一个月掌握VC++2010?
    细说Angular ngclass
    2013 北京 QCon热点分享
    RadioButtonList
    NSubstitute完全手册1
    使用MEF实用IOC(依赖倒置)
    发布订阅模式 之 同步订阅、异步订阅和离线订阅
  • 原文地址:https://www.cnblogs.com/Knuth/p/2191799.html
Copyright © 2020-2023  润新知