HDU 3038 How Many Answers Are Wrong Problem Solving report weighted disjoint-set

HDU 3038 How Many Answers Are Wrong Problem Solving Report

Problem-solving ideas: meaning of the questions is to give multiple sets of intervals and, there will be several groups of wrong data, so that you the number of erroneous data sets to calculate, when the two sets of data conflict, a set of data to be given is correct. With disjoint-set, while continuously updating each node weights root and (weights and may be negative), and finally pay attention while the input of n and m, otherwise wa. Look at the code, added a note.
Here Insert Picture Description

#include <stdio.h>
#include<iostream>
#include <algorithm>
#include<string.h>
#include<cmath>
#pragma warning(disable:4996)
#define mod 1000000007
#define ll unsigned long long
const int N = 200005;
using namespace std;
int sum[N];//记录某点到其根节点的权值和,注意不是前缀和
int father[N];
int find(int x)
{
	if (x != father[x])
	{
		int tem = father[x];//记录x的上一级
		father[x] = find(father[x]);//更新最高上级,即路径压缩
		sum[x] += sum[tem];//记录权值和
	}
	return father[x];
}
int main()
{
	int ans, n, m;
	while (~scanf("%d%d", &n, &m))
	{
		ans = 0;
		memset(sum, 0,sizeof(sum));
		for (int i = 0; i <= n; i++)
		{
			father[i] = i;
		}
		int head, ed, val;
		while (m--)
		{
			scanf("%d%d%d", &head, &ed, &val);
			head--;//因为后面要用sum减出区间和,所以开头减1,这样减出来的值就包括在head位置的数
			int fh = find(head);
			int fe = find(ed);
			if (fh == fe)
			{
				if (sum[head] - sum[ed] != val)
					ans++;
			}
			else
			{
				father[fh] = fe;
				sum[fh] = val + sum[ed] - sum[head];//注意到根节点的值可能是负值
			}
		}
		printf("%d\n", ans);
	}
}


Published 64 original articles · won praise 0 · Views 1439

Guess you like

Origin blog.csdn.net/weixin_45566331/article/details/105057121