#include <bits/stdc++.h>
/*
Phia ben kia dai duong cung chi co
Bo cat nang niu bien thoi
*/
using namespace std;
using ll = long long;
#define int long long
#define pii pair<ll, ll>
#define fi first
#define se second
const ll N = 5e5 + 5, inf = 1e18, mod = 1e9 + 7, block = 320, lim = 19;
int n, k;
vector <int> adj[N], grp[N];
struct DSU {
int par[N];
void makeset() {
for (int i = 1; i <= n; i++) {
par[i] = i;
}
}
int find(int u) {
if (par[u] == u) return u;
return par[u] = find(par[u]);
}
void join(int u, int v) {
u = find(u), v = find(v);
if (u != v) {
par[v] = u;
}
}
} dsu;
int par[N], depth[N];
int on[N];
void dfs(int u, int parent) {
par[u] = parent;
for (auto v : adj[u]) {
if (v != parent) {
depth[v] = depth[u] + 1;
dfs(v, u);
}
}
}
void merge(int a, int b) {
a = dsu.find(a), b = dsu.find(b);
while(a != b) {
// cout << a << ' ' << b << ' ' << depth[a] << ' ' << depth[b] << '\n';
if (depth[a] > depth[b]) swap(a, b);
// cout << a << ' ' << b << ' ' << depth[a] << ' ' << depth[b] << '\n';
// cout << "at: " << par[b] << '\n';
dsu.join(par[b], b);
// cout << b << ' ' << par[b] << ' ' << dsu.find(par[b]) << dsu.find(2) << '\n';
b = dsu.find(par[b]);
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
if (fopen(".inp", "r")) {
freopen(".inp", "r", stdin);
freopen(".out", "w", stdout);
}
cin >> n >> k;
dsu.makeset();
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, 0);
// for (int i = 1; i <= n; i++) cout << par[i] << ' ';
// cout << '\n';
// cout << dsu.find(2) << '\n';
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
grp[x].push_back(i);
}
for (int i = 1; i <= k; i++) {
if (grp[i].size() < 2) continue;
for (int j = 1; j < grp[i].size(); j++) {
merge(grp[i][0], grp[i][j]);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (auto v : adj[i]) {
int x = dsu.find(i), y = dsu.find(v);
if (x != y) {
if (on[x] == 0) ans++;
else if (on[x] == 1) ans--;
on[x]++;
}
}
}
cout << (ans + 1) / 2;
return 0;
}
Compilation message (stderr)
mergers.cpp: In function 'int main()':
mergers.cpp:68:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
68 | freopen(".inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~
mergers.cpp:69:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
69 | freopen(".out", "w", stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~
# | 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... |