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>
#define ll long long
#define ull unsigned ll
#define f first
#define s second
#define pii pair<ll,ll>
#define pll pair<ll,ll>
#define pb push_back
#define epb emplace_back
using namespace std;
const int nmax = 5e5 + 1;
int in[nmax], out[nmax];
int timer = 0;
int p[nmax][22];
vector <vector <int> > g(nmax);
void dfs(int v, int e){
in[v] = timer++;
p[v][0] = e;
for(int j = 1; j <= 20; j++)
p[v][j] = p[p[v][j - 1]][j - 1];
for(int to : g[v]){
if(to == e) continue;
dfs(to, v);
}
out[v] = timer++;
}
bool isancestor(int u, int v){
return in[u] <= in[v] && out[u] >= out[v];
}
int lca(int u, int v){
if(isancestor(u, v)) return u;
if(isancestor(v, u)) return v;
for(int j = 20; j >= 0; j--){
if(!isancestor(p[u][j], v)) u = p[u][j];
}
return p[u][0];
}
vector <int> sz(nmax);
vector <int> a(nmax);
int c = 0;
void DFS(int v, int e){
sz[v] = 1;
for(int to : g[v]){
if(to == e) continue;
DFS(to, v);
sz[v] += sz[to];
}
sz[v] -= a[v];
if(sz[v] == 0) c++;
}
int cnt[nmax];
int leaf = 0;
void ansdfs(int v, int cur, int e){
if(sz[v] == 0 && cur != v) cnt[v]++, cnt[cur]++;
if(sz[v] == 0) cur = v;
for(int to : g[v]){
if(to != e)
ansdfs(to, cur, v);
}
if(cnt[v] == 1) leaf++;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
int n; cin >> n;
int k; cin >> k;
vector <vector <int> > vec(k + 1);
for(int i = 1; i < n; i++){
int u, v; cin >> u >> v;
g[u].pb(v); g[v].pb(u);
}
dfs(1, 1);
for(int i = 1; i <= n; ++i){
int x; cin >> x;
vec[x].pb(i);
}
for(int i = 1; i <= k; i++){
if(vec[i].empty()) continue;
int lc = vec[i][0];
for(int to : vec[i]) lc = lca(lc, to);
a[lc] += vec[i].size();
}
DFS(1, 1);
if(c == 1) cout << 0 << "\n";
else{ansdfs(1, 1, 1);
cout << ( leaf + 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... |