码迷,mamicode.com
首页 > 其他好文 > 详细

D - Harmonious Graph(并查集)(此题需补)

时间:2019-12-02 01:18:51      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:const   ++   ace   stream   pre   cpp   多少   max   cin   

题意:一共n个点,m条线

若点a连通点b  则对于任何a<c<b,a均与b连通,若不连通,则你需要加边上去

问你需要加多少条边

采用并查集是因为 对于所有小于b并且与b连通的a  均用并查集代替

而其中一个点并查集不等于最大的b时 就需要加边上去  ans++

#include<iostream>
#include<map>
#include<algorithm>
#include<set>
using namespace std;
const int maxn = 2e5+10;

int f[maxn];
int n,m;


int Find(int x)
{
    if(f[x]==x) return x;
    f[x]=Find(f[x]);
    return f[x];
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)    f[i]=i;
    while(m--)
    {
        int x,y,fx,fy;
        cin>>x>>y;
        fx=Find(x);
        fy=Find(y);
        if(fx>fy) swap(fx,fy);
        f[fx]=fy;
    }
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        int x=Find(i);
        while(i<x)
        {
            int y=Find(i);
            if(x!=y)
            {
                ans++;
                if(x<y) swap(x,y);
                f[y]=x;
            }
            i++;
        }
    }
    cout<<ans<<endl;
    return 0;
}

  

D - Harmonious Graph(并查集)(此题需补)

标签:const   ++   ace   stream   pre   cpp   多少   max   cin   

原文地址:https://www.cnblogs.com/AAAzhuo/p/11968470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!