HDU-3038-How Many Answers Are Wrong【 带权并查集 】题解
Then, FF can choose a continuous subsequence from it(for example the subsequence from the third to the fifth integer inclusively). After that, FF will ask TT what the sum of the subsequence he chose is. The next, TT will answer FF’s question. Then, FF can redo this process. In the end, FF must work out the entire sequence of integers.
Boring~Boring~a very very boring game!!! TT doesn’t want to play with FF at all. To punish FF, she often tells FF the wrong answers on purpose.
The bad boy is not a fool man. FF detects some answers are incompatible. Of course, these contradictions make it difficult to calculate the sequence.
However, TT is a nice and lovely girl. She doesn’t have the heart to be hard on FF. To save time, she guarantees that the answers are all right if there is no logical mistakes indeed.
What’s more, if FF finds an answer to be wrong, he will ignore it when judging next answers.
But there will be so many questions that poor FF can’t make sure whether the current answer is right or wrong in a moment. So he decides to write a program to help him with this matter. The program will receive a series of questions from FF together with the answers FF has received from TT. The aim of this program is to find how many answers are wrong. Only by ignoring the wrong answers can FF work out the entire sequence of integers. Poor FF has no time to do this job. And now he is asking for your help~(Why asking trouble for himself~~Bad boy)
Input
Line 1: Two integers, N and M (1 <= N <= 200000, 1 <= M <= 40000). Means TT wrote N integers and FF asked her M questions.
Line 2…M+1: Line i+1 contains three integer: Ai, Bi and Si. Means TT answered FF that the sum from Ai to Bi is Si. It’s guaranteed that 0 < Ai <= Bi <= N.
You can assume that any sum of subsequence is fit in 32-bit integer.
Output
A single line with a integer denotes how many answers are wrong.
Sample Input
10 5
1 10 100
7 10 28
1 3 32
4 6 41
6 6 1
Sample Output
1
2.题意
有 M 个数,不知道它们具体的值,但是知道某两个数之间(包括这两个数)的所有数之和,现在给出 N 个这样的区间和信息,需要判断有多少个这样的区间和与前边已知的区间和存在矛盾。
3.思路
带权并查集,将闭区间的某一端变成开区间。如果给定区间的两个端点属于同一个并查集,判断这个区间的值是否与计算得到的值相等;如果给定区间的两个端点不属于同一个并查集,将这两个并查集合并。并查集边的权值就等于题干中的区间和。
4.代码
#define _C
RT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 2e5 + 10;
int Sum[maxn], Fa[maxn];
void init(int n) //初始化
{
for (int i = 0; i <= n; i++)
{
Fa[i] = i;
Sum[i] = 0;
}
}
int find(int x) //查询
{
if (x != Fa[x])
{
int tmp = Fa[x];
Fa[x] = find(Fa[x]); //将 x 的父节点设置为根节点
Sum[x] += Sum[tmp];
}
return Fa[x];
}
int main()
{
int n, m;
while (cin>>n>>m)
{
init(n);
int ans = 0;
while (m--)
{
int l, r, value;
cin >> l >> r >> value;
l--; //将左闭区间变为开区间
int x = find(l),y=find(r);
评论