zoukankan      html  css  js  c++  java
  • 并查集 带压缩路径的版本

    #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
    ****************************************************************/
  • 相关阅读:
    Python单例模式中的4种方式
    Python list,tuple,dict,set高级变量常用方法
    python如何获取多个excel单元格的值
    两种方法实现python操作日志的封装
    numpy中函数shape的用法
    python中timer定时器常用的两种实现方法
    详解Python中argpasrse模块的基本使用
    在python中列表删除和多重循环退出
    Python的驻留机制(仅对数字,字母,下划线有效)
    python实现tail -f 功能
  • 原文地址:https://www.cnblogs.com/Knuth/p/2191799.html
Copyright © 2011-2022 走看看