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;
class DisjointSet {
private:
int n;
vector<int> p;
public:
DisjointSet(int n) : n(n) {
p.resize(n);
iota(begin(p), end(p), 0);
}
int Find(int x) {
return p[x] == x ? x : p[x] = Find(p[x]);
}
bool Union(int x, int y) {
x = Find(x);
y = Find(y);
if (x == y) return false;
p[y] = x;
return true;
}
bool IsRoot(int x) {
return p[x] == x;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int N, K;
cin >> N >> K;
vector<vector<int>> adj(N + 1);
for (int i = 0; i < N - 1; i++) {
int u, v;
cin >> u >> v;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
vector<vector<int>> colorList(K);
for (int i = 1; i <= N; i++) {
int c;
cin >> c;
colorList[--c].emplace_back(i);
}
vector<int> par(N + 1);
vector<int> depth(N + 1);
DisjointSet group(N + 1);
function<void(int)> Dfs = [&](int n) {
for (auto i : adj[n]) if (i != par[n]) {
depth[i] = depth[n] + 1;
par[i] = n;
Dfs(i);
}
};
auto Unite = [&](int a, int b) {
a = group.Find(a);
b = group.Find(b);
while (a != b) {
if (depth[a] > depth[b]) swap(a, b);
group.Union(par[b], b);
b = group.Find(b);
}
};
depth[1] = 1;
par[1] = 0;
Dfs(1);
for (int k = 0; k < K; k++) {
for (int i = 1; i < (int) colorList[k].size(); i++) {
Unite(colorList[k][0], colorList[k][i]);
}
}
vector<int> degree(N + 1, 0);
for (int i = 1; i <= N; i++) {
for (auto j : adj[i]) {
if (group.Find(i) != group.Find(j)) {
degree[group.Find(i)]++;
}
}
}
int ans = 0;
for (int i = 1; i <= N; i++) {
if (group.IsRoot(i) && degree[i] == 1) {
ans++;
}
}
cout << ((ans + 1) / 2) << "\n";
return 0;
}
# | 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... |