[HDU] [3038] How Many Answers Are Wrong

Problem Description

Loading...

Problem Analysis

Note that a value of 0 does not necessarily mean it is really 0
rather, the given data simply hasn’t been checked against it

So the Template needs the following changes:

When find locates the root, it must compute and store the sum from 1 to itself
let its own value add the parent’s value
and in this process, through Recursion
make the parent’s value add its own parent’s value
while also performing path compression
so that it connects directly to the root
since the root has no data before it to become its parent
sum[root] should always be 0
thus, while finding the root, the computation of the interval value from itself to the root is completed

For the unite merge operation
the idea is
if the two numbers have the same root, then check
otherwise compute the sum interval according to the size of the two roots
then merge according to the relation of the two numbers

Because sum stores its value to the root
the order of a, b is determined, and the assignment follows

(It seems there are other approaches, but I think the more complex the problem, the more ways there sometimes are to solve it, so I won’t force myself to fully understand everyone else’s other approaches)

AC code:
note that there are multiple test cases

cp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<stdio.h>
int par[200200];
int sum[200200];
int cnt,t;
int find(int m) {
	if(par[m]==m)
		return m;
	else {
		int t=par[m];
		par[m]=find(par[m]);
		sum[m]+=sum[t];
		return par[m];
	}
}
void unite(int x,int y) {
	int a=find(x);
	int b=find(y);
	if(a==b) {
		if(sum[y]-sum[x]!=t)
			cnt++;
		return ;
	}
	if(a>b) {
		sum[a]=sum[y]-sum[x]-t;
		par[a]=b;
	} else {
		sum[b]=sum[x]+t-sum[y];
		par[b]=a;
	}
}
int main() {
	int N,M;
	while(scanf("%d %d",&N,&M)!=EOF) {
		cnt=0;
		for(int i=0; i<=N; i++) {
			par[i]=i;
			sum[i]=0;
		}
		while(M--) {
			int a,b;
			scanf("%d %d %d",&a,&b,&t);
			unite(a-1,b);
		}
		printf("%d\n",cnt);
	}
	return 0;
}

Problem link: 【杭电】[3038]How Many Answers Are Wrong

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...