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;
vector<int> haha[500001];
vector<int> col[500001];
vector<int> dep(500001);
vector<int> br(500001);
vector<int> wow[500001];
int bruh[500001][20];
int lca(int a, int b) {
if(dep[a] < dep[b]) {
swap(a,b);
}
int c = dep[a]-dep[b];
for(int i = 19; i >= 0; i--) {
if((1 << i)&c) {
a = bruh[a][i];
}
}
for(int i = 19; i >= 0; i--) {
if(bruh[a][i] != -1 && bruh[a][i] != bruh[b][i]) {
a = bruh[a][i];
b = bruh[b][i];
}
}
if(a == b) {
return a;
}
else {
return bruh[a][0];
}
}
void dfs(int a, int t, int d) {
dep[a] = d+1;
bruh[a][0] = t;
for(int v: haha[a]) {
if(v != t) {
dfs(v,a,d+1);
}
}
}
void dude(int a, int t) {
for(int v: haha[a]) {
if(v != t) {
dude(v,a);
br[a]+=br[v];
}
}
}
void banana(int a, int t, int l) {
if(br[a] == 0) {
if(l != -1) {
wow[a].push_back(l);
wow[l].push_back(a);
}
l = a;
}
for(int v: haha[a]) {
if(v != t) {
banana(v,a,l);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n,k,a,b;
cin >> n >> k;
for(int i = 0; i < n-1; i++) {
cin >> a >> b;
haha[a].push_back(b);
haha[b].push_back(a);
}
dfs(1,-1,0);
for(long long i = 1; i < 20; i++) {
for(long long j = 1; j <= n; j++) {
if(bruh[j][i-1] == -1) {
bruh[j][i] = -1;
}
else {
bruh[j][i] = bruh[bruh[j][i-1]][i-1];
}
}
}
for(int i = 1; i <= n; i++) {
cin >> a;
col[a].push_back(i);
}
for(int i = 1; i <= k; i++) {
int c = col[i][0];
for(int v: col[i]) {
br[v]++;
c = lca(c,v);
}
br[c]-=col[i].size();
}
dude(1,-1);
banana(1,-1,-1);
int ans = 0;
for(int i = 1; i <= n; i++) {
if(wow[i].size() == 1) {
ans++;
}
}
if(ans == 1) {
cout << 0;
}
else {
cout << (ans+1)/2;
}
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... |