2021 Niu Ke Winter Holiday Algorithm Basic Training Camp 3 G. Candy (and check collection)

G. Candy

Title link: https://ac.nowcoder.com/acm/contest/9983/G

Title description:

There are n children in a kindergarten, numbered 1, 2, ..., n respectively. Some of these children are friends with each other, and there are m pairs of friends in total.
As a kindergarten teacher, you want to buy some candies to distribute to children. You know that the i-th child wants at least ai candies, otherwise he will be unhappy. At the same time, if the number of candies obtained by a child is less than the number of candies obtained by one of his friends, he will also be unhappy.
How much candy do you buy at least to ensure that every child will not be unhappy?

Enter a description:

Two integers n, m separated by a space on the first line.
On the second line, n positive integers ai separated by spaces.
In the next m line, each line is separated by two positive integers u, v, representing that u is a friend of v, and v is a friend of u.
1≤n≤10^6
0≤m≤10^6
1≤ai≤10^9
1≤u,v≤n,u≠v

Output description:

The minimum number of candies purchased to ensure that every child will not be unhappy.

Example 1:

Enter
3 1
1 2 3
1 2 and
output
7
Description
Buy 3 candies for the third child, and the first two children both buy 2 candies, and buy at least 7 candies in total. Note that if you buy only 1 candy for the first child, he will be unhappy when he sees that his good friend 2 has 2 candy.

Problem-solving ideas:

People who are good friends of each other get the same number of candies, and it is the maximum value among all the good friends candies of the child (and the maximum value collected). It should be noted that m is to children, and children’s children are not necessarily good friends.

code show as below:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef long long ll;
ll f[1000010],a[1000010];
int find(int x){
    
    
	if(x==f[x])return x;
	return f[x]=find(f[x]);
}
int main(){
    
    
	ll n,m,x,y,ans=0;
	cin>>n>>m;
	for(int i=1;i<=n;i++){
    
    
		cin>>a[i];
		f[i]=i;
	}
	for(int i=1;i<=m;i++){
    
    
		cin>>x>>y;
		ll t1=find(x),t2=find(y);
		f[t1]=t2;  //合并互为朋友关系
		a[t2]=max(a[t1],a[t2]);  //更新最大值
	}
	for(int i=1;i<=n;i++)
		ans+=a[find(i)];
	cout<<ans<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/113730864