Submission #482840

#TimeUsernameProblemLanguageResultExecution timeMemory
482840rainboySjekira (COCI20_sjekira)C11
110 / 110
69 ms8172 KiB
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N	100000

int max(int a, int b) { return a > b ? a : b; }

unsigned int X = 12345;

int rand_() {
	return (X *= 3) >> 1;
}

int *ej[N], eo[N];

void append(int i, int j) {
	int o = eo[i]++;

	if (o >= 2 && (o & o - 1) == 0)
		ej[i] = (int *) realloc(ej[i], o * 2 * sizeof *ej[i]);
	ej[i][o] = j;
}

int aa[N];

void sort(int *ii, int l, int r) {
	while (l < r) {
		int i = l, j = l, k = r, i_ = ii[l + rand_() % (r - l)], tmp;

		while (j < k)
			if (aa[ii[j]] == aa[i_])
				j++;
			else if (aa[ii[j]] < aa[i_]) {
				tmp = ii[i], ii[i] = ii[j], ii[j] = tmp;
				i++, j++;
			} else {
				k--;
				tmp = ii[j], ii[j] = ii[k], ii[k] = tmp;
			}
		sort(ii, l, i);
		l = k;
	}
}

int ds[N];

int find(int i) {
	return ds[i] < 0 ? i : (ds[i] = find(ds[i]));
}

int join(int i, int j) {
	int a;

	i = find(i);
	j = find(j);
	if (i == j)
		return 0;
	a = aa[i] + aa[j], aa[i] = aa[j] = max(aa[i], aa[j]);
	if (ds[i] > ds[j])
		ds[i] = j;
	else {
		if (ds[i] == ds[j])
			ds[i]--;
		ds[j] = i;
	}
	return a;
}

int main() {
	static int ii[N];
	static char alive[N];
	int n, h, i, j, o;
	long long ans;

	scanf("%d", &n);
	for (i = 0; i < n; i++) {
		scanf("%d", &aa[i]);
		ej[i] = (int *) malloc(2 * sizeof *ej[i]);
	}
	for (h = 0; h < n - 1; h++) {
		scanf("%d%d", &i, &j), i--, j--;
		append(i, j), append(j, i);
	}
	for (i = 0; i < n; i++)
		ii[i] = i;
	sort(ii, 0, n);
	memset(ds, -1, n * sizeof *ds);
	ans = 0;
	for (h = 0; h < n; h++) {
		i = ii[h];
		alive[i] = 1;
		for (o = eo[i]; o--; ) {
			j = ej[i][o];
			if (alive[j])
				ans += join(i, j);
		}
	}
	printf("%lld\n", ans);
	return 0;
}

Compilation message (stderr)

sjekira.c: In function 'append':
sjekira.c:20:23: warning: suggest parentheses around '-' in operand of '&' [-Wparentheses]
   20 |  if (o >= 2 && (o & o - 1) == 0)
      |                     ~~^~~
sjekira.c: In function 'main':
sjekira.c:76:2: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
   76 |  scanf("%d", &n);
      |  ^~~~~~~~~~~~~~~
sjekira.c:78:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
   78 |   scanf("%d", &aa[i]);
      |   ^~~~~~~~~~~~~~~~~~~
sjekira.c:82:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
   82 |   scanf("%d%d", &i, &j), i--, j--;
      |   ^~~~~~~~~~~~~~~~~~~~~
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...