The 11th Blue Bridge Cup network analysis with power and collection

Idea : Either merge the two sets, or add numbers to all nodes in the set. The
d array represents the difference between the current node and the root node, and the b array represents the number to be added to all the numbers in the set where the root node is located .
Note that when merging, the d array of the point as the son node should be updated to the difference between the original two sets. The
final answer for each number is the value of the block plus the difference between itself and the set where the block is located.

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+50;
int f[N],d[N],b[N];
int find(int x){
    
    
	if(f[x]!=x){
    
    
		int fa=f[x];
		f[x]=find(f[x]);
		d[x]+=d[fa];
	}
	return f[x];
}
int main(){
    
    
	int n,m;cin>>n>>m;
	for(int i=1;i<=n;i++) f[i]=i;
	while(m--){
    
    
		int op,x,y;cin>>op>>x>>y;
		if(op==1){
    
    
			int fx=find(x),fy=find(y);
			if(fx!=fy){
    
    
				f[fx]=fy;
				d[fx]=b[fx]-b[fy];
			}
		}
		else b[find(x)]+=y;
	}
	for(int i=1;i<=n;i++) cout<<b[find(i)]+d[i]<<" ";
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43563669/article/details/109988606