#include<bits/stdc++.h>
#define taskname "B"
using namespace std;
const int lim = 5e5 + 5;
int n, k, parent[lim], h[lim], p[lim], vertex[lim], d[lim];
vector<int>g[lim];
int find_set(int N){
return N == p[N] ? N : p[N] = find_set(p[N]);
}
void merge(int a, int b){
if((a = find_set(a)) != (b = find_set(b))){
if(h[a] > h[b]){
swap(a, b);
}
p[b] = a;
}
}
void move(int a, int b){
while(a != b){
if(h[a] < h[b]){
swap(a, b);
}
merge(a, parent[a]);
a = find_set(parent[a]);
}
}
void dfs(int s){
for(int& d : g[s]){
if(d != parent[s]){
h[d] = h[parent[d] = s] + 1;
dfs(d);
}
}
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
if(fopen(taskname".inp", "r")){
freopen(taskname".inp", "r", stdin);
}
cin >> n >> k;
for(int i = 1; i < n; i++){
int u, v;
cin >> u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
dfs(parent[1] = h[1] = 1);
memset(vertex, -1, sizeof(vertex));
iota(p + 1, p + n + 1, 1);
for(int i = 1; i <= n; i++){
int x;
cin >> x;
if(vertex[x] == -1){
vertex[x] = i;
}
else{
move(vertex[x], i);
}
}
int cnt = 0;
memset(d, 0, sizeof(d));
for(int i = 1; i <= n; i++){
for(int& j : g[i]){
if(find_set(i) != find_set(j)){
if(d[find_set(i)]++ == 0){
cnt++;
}
else if(d[find_set(i)] == 2){
cnt--;
}
}
}
}
cout << ((cnt + 1) >> 1);
}
Compilation message (stderr)
mergers.cpp: In function 'int main()':
mergers.cpp:38:24: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
38 | freopen(taskname".inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |