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;
using ll = long long;
#define x first
#define y second
ll N, K, A[500005], D[500005], P[500005];
vector<ll> T[500005];
struct UnionFind{
ll p[500005];
ll Find(ll n) { return (p[n] < 0 ? n : p[n] = Find(p[n])); }
void Union(ll u, ll v) { u = Find(u), v = Find(v); if(u != v) p[u] += p[v], p[v] = u; }
}uf;
void dfs(ll u, ll p){
P[u] = p;
for(auto v : T[u]){
if(v == p) continue;
D[v] = D[u] + 1;
dfs(v, u);
}
}
void Comp(ll u, ll v){
u = uf.Find(u), v = uf.Find(v);
while(u != v){
if(D[u] < D[v]) swap(u, v);
uf.Union(P[u], u);
u = uf.Find(P[u]);
}
}
vector<ll> S[500005];
ll deg[500005];
int main(){
cin.tie(0) -> sync_with_stdio(0);
cin >> N >> K;
fill(uf.p, uf.p + N + 1, -1LL);
for(ll i = 1; i < N; i++){
ll u, v; cin >> u >> v;
T[u].push_back(v); T[v].push_back(u);
}
dfs(1, -1);
for(ll i = 1; i <= N; i++){
ll v; cin >> v;
S[v].push_back(i);
}
for(ll i = 1; i <= K; i++){
for(ll j = 1; j < S[i].size(); i++){
Comp(S[i][0], S[i][j]);
}
}
for(ll i = 1; i <= N; i++){
for(auto j : T[i]){
if(i > j) continue;
ll u = uf.Find(i), v = uf.Find(j);
if(u != v) deg[u]++, deg[v]++;
}
}
ll Cnt = 0;
for(ll i = 1; i <= N; i++){
if(deg[i] == 1) Cnt++;
}
cout << (Cnt + 1) / 2;
}
Compilation message (stderr)
mergers.cpp: In function 'int main()':
mergers.cpp:52:25: warning: comparison of integer expressions of different signedness: 'll' {aka 'long long int'} and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
52 | for(ll j = 1; j < S[i].size(); i++){
| ~~^~~~~~~~~~~~~
# | 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... |