• codeforces1253——D. Harmonious Graph(并查集)


    原题链接
    题意:
    定义一张无向图是和谐的当且仅当:假设图中存在一条从 l 到 rr(l<r)的路径,则图中也存在从 l 到 l+1,l+2,……,r−1 的路径。
    给出一张无向图,求至少需要添加多少条边才能将其变为和谐的。
    思路:
    可以发现对于每个连通块来说,如果最大值和最小值之间有数不属于该连通块,就是连边。
    用并查集维护每个连通块并保证每个连通块的根节点都是最大值。再遍历一遍节点,对于每个节点暴力的计算出每个节点和根节点之间的点是否在该连通块内,不是的话就加边,加边的时候也要保证根节点是最大值。
    对于加边的部分,还有一种优化
    代码:

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    typedef unsigned long long ull;
    typedef pair<ll,ll>PLL;
    typedef pair<int,int>PII;
    typedef pair<double,double>PDD;
    #define I_int ll
    inline ll read()
    {
        ll x=0,f=1;char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
        while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
        return x*f;
    }
    char F[200];
    inline void out(I_int x) {
        if (x == 0) return (void) (putchar('0'));
        I_int tmp = x > 0 ? x : -x;
        if (x < 0) putchar('-');
        int cnt = 0;
        while (tmp > 0) {
            F[cnt++] = tmp % 10 + '0';
            tmp /= 10;
        }
        while (cnt > 0) putchar(F[--cnt]);
        //cout<<" ";
    }
    ll ksm(ll a,ll b,ll p){ll res=1;while(b){if(b&1)res=res*a%p;a=a*a%p;b>>=1;}return res;}
    const int inf=0x3f3f3f3f,mod=998244353;
    const ll INF = 0x3f3f3f3f3f3f3f3f;
    const int maxn=2e5+100,maxm=3e5+7,N=1e6+7;
    const double PI = atan(1.0)*4;
    
    int root[maxn];
    int Find(int x){
        if(x!=root[x]) root[x]=Find(root[x]);
        return root[x];
    }
    int main(){
        int n=read(),m=read(),cnt=0;
        for(int i=1;i<=n;i++) root[i]=i;
        while(m--){
            int u=read(),v=read();
            u=Find(u),v=Find(v);
            if(u!=v){
                ///v是最大的
                if(v<u) swap(u,v);
                root[u]=v;
            }
        }
        int res=0;
        for(int i=1;i<=n;i++){
            int fa=Find(i);
            while(i<fa){
                int x=Find(i);
                if(x!=fa){
                    if(fa<x) swap(fa,x);
                    root[x]=fa;
                    res++;
                }
                i++;
            }
        }
        out(res);
        return 0;
    }
    
    
  • 相关阅读:
    【扩展】1. PHP 大括号{} 的使用
    preg_replace 中修正符 e 的解析
    terminal 修改终端显示的名字
    find 命令详解
    OSI 7层结构 粗认识
    vi 全解析
    awk 学习笔记
    scp 复制远程文件 文件带空格 处理
    更新博客地址啦!!!
    ubuntu16.04安装NVIDIA驱动遇到的问题
  • 原文地址:https://www.cnblogs.com/OvOq/p/14853089.html
Copyright © 2020-2023  润新知