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

简介: 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;
}
目录
相关文章
|
10月前
UVa872 - Ordering(拓扑排序)
UVa872 - Ordering(拓扑排序)
49 0
|
10月前
UVa302 - John's trip(并查集、欧拉回路、DFS)
UVa302 - John's trip(并查集、欧拉回路、DFS)
38 0
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
95 0
AtCoder Beginner Contest 223 D - Restricted Permutation(建图 思维 构造 拓扑排序)
AtCoder Beginner Contest 223 D - Restricted Permutation(建图 思维 构造 拓扑排序)
93 0
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
119 0
HDU-1142,A Walk Through the Forest(Dijkstra+DFS)
HDU-1142,A Walk Through the Forest(Dijkstra+DFS)

热门文章

最新文章