并查集

数据结构-并查集

今天要说的这个数据结构是并查集,一种很好用的东西,刷题也会经常用的。并查集一个比较主要的应用是求最小生成树(克鲁斯卡尔算法)。(并查集是什么,这个在这里就不多说了)还是那句话,话不多说,直接上题:
传送门: https://ac.nowcoder.com/acm/contest/373/C

解析

这道题其实很简单,首先要想的他说强盗会从一个地方移动到另一个地方,很明显,就是告诉你有一条有向边,从 u u u指向 v v v,那么通过分析,这些强盗最后所处的情况无非就两种,一种一直在一个环上循环,另一种是他们都集中到了一个结点。那么一种比较简单的做法就是利用并查集,查找每个结点的祖先,对于环,最后到达的结点就是他们的祖先。

AC代码:

//  小学生一发的刷题之路
//
//  Mannacher Algorithm
//
//

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <deque>                //双向队列;
#include <cmath>
#include <set>
#include <stack>
#include <map>
#include <vector>
#include <cstdlib>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double PI=acos(-1.0);
const double eps=1e-8;
const int maxn=1e5+5;
const int maxm=1e3+5;
const ll mod=1e9+7;
const int INF=1e8;
template<class T>
inline void read(T &ret){       //快速输入模版;
    ret=0;
    int f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        ret=ret*10+c-'0';
        c=getchar();
    }
    ret*=f;
}
template <class T>
inline void out(T ret){     //快速输出模版;
    if(ret>9)
    {
        out(ret/10);
    }
    putchar(ret%10+'0');
}
int n,m;
ll a[maxn],pre[maxn];

int find(int x){       //查找结点x的祖先;
    int r=x;
    while(pre[r]!=r){
        r=pre[r];
    }
    
    int tmp;
    while(x!=r){        //路径压缩;
        tmp=pre[x];
        pre[x]=r;
        x=tmp;
    }
    return r;
}

bool cmp(int x,int y){
    return x>y;
}

int main()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        pre[i]=i;
    }
    
    int v;
    for(int i=1;i<=n;i++){
        scanf("%d",&v);
        if(v==i){
            continue;
        }
        int fi=find(i);
        int fv=find(v);
        if(fi==fv){     //出现环;
            continue;
        }
        a[fv]+=a[fi];
        a[fi]=0;
        pre[fi]=fv;
    }
    sort(a+1,a+1+n,cmp);
    ll sum=0;
    for(int i=1;i<=m;i++){
        sum+=a[i];
    }
    printf("%lld\n",sum);
    return 0;
}

新的开始,每天都要快乐哈!
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值