C - Rumor CodeForces - 893C

简介: C - Rumor CodeForces - 893C

一些话


拆解流程的时候没想到res 开long long,但写的时候想到了,一开始还庆幸自己这次这么机灵,结果debug一直de不出错误点,还是靠学长提醒才发现printf没有用%lld。。。


还有一开始用标准find然后tle,以后还是都用路径压缩find好了


自己总结的路径压缩find套路有瑕疵,一直没发现,也是靠学长指点才发现错误。。


流程

父节点数组

值数组

find注意此题卡路径压缩

标准un加一个值比较,小的做父节点


编号1-n,q次关系


fori = 1 I <= n


读入值


whileq--


读入a,b


un(a,b)


while外查询并查集数


cnt改为res ,res += v[i] 注意res要开long long


cout << res < < end; 注意res开long long 后printf参数要改成%lld


套路

1、路径压缩find

条件:并查集必用

形式一:

int find(int x){
    if(f[x] != x) f[x] = find(f[x];
    return f[x];
}


形式二:

1. int find(int x){
2. return f[x] == x ? x : f[x] = find(f[x]);
3. }


网络上还存在一种很长的形式三仅展示,不推荐使用:

int find(int x)
{
    int r=x;
    while(f[r]!=r)
    r=f[r];
    int i=x;
    int j;
    while(i!=r)
    {
        j=f[i];
        f[i]=r;
        i=j;
    }
    return r;
}

ac代码

#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int f[N],v[N];
int find(int x){
  if(f[x] != x) f[x] = find(f[x]);
  return f[x];
}
void un(int a, int b){
  int fa = find(a);
  int fb = find(b);
  if(fa != fb){
    if(v[fa] > v[fb]) f[fa] = fb;
    else f[fb] = fa;
  }
}
int main(){
  int n,q;
  scanf("%d%d",&n,&q);
  for(int i = 1;i <= n;i++){
    f[i] = i;
    scanf("%d",&v[i]);
  }
  while(q--){
    int a, b;
    scanf("%d%d",&a,&b);
    un(a,b);
  }
  long long res = 0;
  for(int i = 1 ;i <= n;i++){
    if(f[i] == i) res += v[i];
  }
  printf("%lld",res);
  return 0;
}
目录
相关文章
|
6月前
codeforces 322 B Ciel and Flowers
有红绿蓝三种颜色的画,每种拿三朵可以组成一束花,或者各拿一朵组成花束,告诉你每种花的数目,求出可能组成最多的花束。 如果你的代码过不了,考虑一下 8 8 9这种组合。 因为数据量很大,我的思想就是局部和总体采用不同的策略。
26 0
|
6月前
codeforces 322 A Ciel and Dancing
有n个男孩和m个女孩,他们要结对跳舞,每对要有一个女孩和一个男孩,而且其中一个要求之前没有和其他人结对,求出最大可以结多少对。
21 0
|
6月前
|
C++
codeforces 305 C. Ivan and Powers of Two
我的思路是这样的,由2^a+2^a = 2^(a+1)可知,如果有两个连续的数a,我们可以把他们合并为a+1放入集合中,使集合中没有重复的数,我可以用stl里的set。如果想要满足题目中的要求,集合中必须有最大那个数个元素,缺多少就可以计算出来了。
15 0
Codeforces 833E Caramel Clouds
E. Caramel Clouds time limit per test:3 seconds memory limit per test:256 megabytes input:standard input output:standard out...
1129 0
|
机器学习/深度学习 人工智能 网络架构
Codeforces 706B Interesting drink
B. Interesting drink time limit per test:2 seconds memory limit per test:256 megabytes input:standard input output:standard outp...
1137 0
Codeforces 591B Rebranding
B. Rebranding time limit per test:2 seconds memory limit per test:256 megabytes input:standard input output:standard output ...
829 0
|
人工智能
Codeforces 719B Anatoly and Cockroaches
B. Anatoly and Cockroaches time limit per test:1 second memory limit per test:256 megabytes input:standard input output:stan...
862 0