【带权并查集】 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值