// __builtin_popcount(x)
// __builtin_popcountll(x)
#define here cerr<<"===========================================\n"
#include <bits/stdc++.h>
#define ld double
#define ll long long
#define ull unsigned long long
#define llinf 100000000000000000LL // 10^17
#define iinf 2000000000 // 2*10^9
#define pb push_back
#define popb pop_back
#define fi first
#define sc second
#define endl '\n'
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pld pair<ld,ld>
#define sz(a) int(a.size())
#define all(a) a.begin(),a.end()
#define ceri(a,l,r) {for(ll i_ = l;i_<=r;i_++) cerr<<a[i_]<< " ";cerr<<endl;}
using namespace std;
#define maxn 500005
ll n,k;
vector<ll> g[maxn];
vector<ll> v;
ll a[maxn];
ll in[maxn];
ll out[maxn];
ll dp[maxn][3];
ll b[maxn][3];
ll it = 1;
void dfs(ll u,ll par){
in[u] = it++;
for(ll s : g[u]){
if(s==par) continue;
dfs(s,u);
}
out[u] = it-1;
}
bool intree(ll x,ll i){
return x>=in[i]&&out[i]>=x;
}
bool bio[maxn];
ll ans = 0;
void dfs2(ll u,ll par){
dp[u][1] = b[a[u]][1];
dp[u][2] = b[a[u]][2];
for(ll s : g[u]){
if(s==par) continue;
dfs2(s,u);
dp[u][1] = min(dp[u][1],dp[s][1]);
dp[u][2] = max(dp[u][2],dp[s][2]);
bio[u]|=bio[s];
}
bool da = 0;
if(u!=par){
if(intree(dp[u][1],u)&&intree(dp[u][2],u)) da = 1;
}
if((bio[u]==0)&&(da==1)){
ans++;
cerr<<"u: "<<u<<" "<<dp[u][1]<< " "<<dp[u][2]<<endl;
}
bio[u]|=da;
}
int main(){
ios_base::sync_with_stdio(false);cerr.tie(0);cout.tie(0);cin.tie(0);
cin >> n >> k;
for(ll i = 1;i<=n-1;i++){
ll x,y; cin >> x >> y;
g[x].pb(y);
g[y].pb(x);
}
for(ll i = 1;i<=n;i++) cin >> a[i];
dfs(1,1);
for(ll i = 1;i<=k;i++){
b[i][1] = llinf;
b[i][2] = 0;
}
for(ll i = 1;i<=n;i++){
ll col = a[i];
b[col][1] = min(b[col][1],in[i]);
b[col][2] = max(b[col][2],in[i]);
}
dfs2(1,1);
ll cnt = 0;
for(ll x : g[1]) if(bio[x]) cnt++;
if(cnt<=1) ans++;
ans = (ans+1)/2;
cout<<ans-1<<endl;
return 0;
}
/*
5 4
1 2
2 3
3 4
3 5
1
2
1
3
4
5 4
1 2
2 3
3 4
4 5
1
2
3
4
1
*/
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
6 ms |
11988 KB |
Output is correct |
2 |
Incorrect |
6 ms |
11988 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
6 ms |
11988 KB |
Output is correct |
2 |
Incorrect |
6 ms |
11988 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
6 ms |
11988 KB |
Output is correct |
2 |
Incorrect |
6 ms |
11988 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
44 ms |
20908 KB |
Output is correct |
2 |
Incorrect |
870 ms |
25208 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
6 ms |
11988 KB |
Output is correct |
2 |
Incorrect |
6 ms |
11988 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |