# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
106174 | mzhao | Mergers (JOI19_mergers) | C++11 | 1811 ms | 177340 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;
#define MN 500100
#define x first
#define y second
int N, K, S[MN], tot[MN], ans, g[MN];
vector<int> adj[MN], adj2[MN];
bool bad[MN];
map<int, int>* m[MN];
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); }
map<int, int>* dfs(int n, int p) {
m[n] = new map<int, int>;
if (tot[S[n]] > 1) (*m[n])[S[n]] = 1;
for (int i : adj[n]) if (i != p) {
map<int, int>* cur = dfs(i, n);
if (cur->size() > m[n]->size()) swap(cur, m[n]);
for (auto j : *cur) {
(*m[n])[j.x] += j.y;
if ((*m[n])[j.x] == tot[j.x]) m[n]->erase(j.x);
}
}
if (p) {
if (m[n]->size() == 0) bad[n] = 1;
else merge(n, p);
}
return m[n];
}
void dfs2(int n, int p) {
if (adj2[n].size() == 1) ans++;
for (int i : adj2[n]) if (i != p) dfs2(i, n);
}
int main() {
scanf("%d%d", &N, &K);
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);
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);
}
dfs2(f(1), 0);
printf("%d\n", (ans+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... |