# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
106172 | mzhao | Mergers (JOI19_mergers) | C++11 | 60 ms | 47584 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#ifdef DEBUG
#define D(x...) printf(x)
#else
#define D(x...)
#endif
#define MN 500100
#define x first
#define y second
int N, K, S[MN];
vector<int> adj[MN];
int tot[MN], cnt[MN], ans, dep[MN], par[MN];
int cur[3100][3100];
bool bad[MN];
int g[3100];
int f(int x) { if (g[x] != x) g[x] = f(g[x]); return g[x]; }
void merge(int a, int b) { if (f(a) != f(b)) g[f(a)] = f(b); }
vector<int> adj2[MN];
void dfs(int n, int p, int d) {
dep[n] = d;
par[n] = p;
for (int i = 1; i <= K; i++) cur[n][i] = cnt[i];
cnt[S[n]]++;
for (int i : adj[n]) if (i != p) {
dfs(i, n, d+1);
}
for (int i = 1; i <= K; i++) cur[n][i] = cnt[i]-cur[n][i];
if (n == 1) return;
bool f = 1;
for (int i = 1; i <= K; i++) if (cur[n][i] && cur[n][i] != tot[i]) {
f = 0;
break;
}
bad[n] = f;
if (!f) merge(n, p);
}
int leaves;
void dfs2(int n, int p) {
if (adj2[n].size() == 1) leaves++;
for (int i : adj2[n]) if (i != p) dfs2(i, n);
}
int main() {
scanf("%d%d", &N, &K);
assert(N <= 3000);
for (int i = 1, A, B; i < N; i++) {
scanf("%d%d", &A, &B);
adj[A].push_back(B);
adj[B].push_back(A);
}
for (int i = 1; i <= N; i++) {
scanf("%d", &S[i]);
tot[S[i]]++;
g[i] = i;
}
dfs(1, 0, 0);
for (int i = 1; i <= N; i++) {
for (int j : adj[i]) {
int a = f(i), b = f(j);
if (a != b) {
adj2[a].push_back(b);
adj2[b].push_back(a);
}
}
}
dfs2(f(1), 0);
printf("%d\n", (leaves+1)/2);
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |