【带权并查集】 How Many Answers Are Wrong

题目描述

给定一个数字n,然后进行m次询问。每次询问给出三个数字ai,bi,si。表示从第ai个数到第bi个数的总和是si。判断每次询问的是正确还是错误,最后输出错误次数

sample input
10 5
1 10 100
7 10 28
1 3 32
4 6 41
6 6 1
sample output
1
样例解释

第一次 第1-10个数之和为100
第二次 第7-10个数之和为28 则第1-6个数之和为72
第三次 第1-3个数之和为32 则第4-6个数之和为40
第四次 第4-6个数之和为41???错了 ans++;
第五次 第6-6个数之和为1 第4-5个数之和为39
所以错误次数为1

思路

把ai和bi看成是结点,si则为权值

如果不懂(和我一开始一样)这边有一个很详细的教法 link.

#include<bits/stdc++.h>
using namespace std;

const int N=200000+10;
int f[N],sum[N];
int ans;

int find(int x) {
	if ( x!=f[x] ) {
		int fx=find(x);
		f[x]=find(f[x]);
		sum[x]+=sum[f[x]];           //这边也就是权值更新了
	}
	return f[x];
}

void unions(int x, int y, int s) {
	int fx=find(x);
	int fy=find(y);
	if ( fx==fy ) {
		if ( sum[x]-sum[y]!=s ) ans++;       //判断是否正确
	}
	else {
		f[fx]=fy;
		sum[fx]=s+sum[y]-sum[x];           //权值变换的永远是父结点
		//sum[fx]+sum[x]==s+sum[y] 画图,那个链接有图
}

int main() {
	int n,m;
	while(~scanf("%d %d",&n,&m)) {
		for(int i=0; i<=n; i++ ) {
			f[i]=i;
			sum[i]=0;
		}
		int a,b,s;
		ans=0;
		while(m--) {
			scanf("%d %d %d",&a,&b,&s);
			unions(a,b,s);
		}
		printf("%d\n",ans);		
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章