#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define fi first
#define se second
#define mp make_pair
#define fastIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N = (int)2e5 + 100;
vector<int> Z[N];
vector<int> T[N];
int id[N];
bool ban[N];
int par[N];
int subt[N];
bool now[N];
vector<int> mark;
void dfs(int u, int pr){
subt[u] = 1;
now[u]=true;
mark.push_back(u);
for(auto x : T[u]){
if(ban[x] || x == pr) continue;
dfs(x, u);
subt[u] += subt[x];
}
}
int up[N];
void dfs1(int u, int pr){
up[u] = pr;
for(auto x : T[u]){
if(ban[x] || x == pr) continue;
dfs1(x, u);
}
}
int fin(int u){
if(par[u]==u)
return u;
return par[u]=fin(par[u]);
}
int res;
void decomp(int node){
mark.clear();
dfs(1, -1);
int pr = -1;
bool is = true;
int sz = subt[node];
while(is){
is = false;
for(auto x : T[node]){
if(x == pr || ban[x]) continue;
if(subt[x] > sz/2){
pr = node;
node = x;
is = true;
break;
}
}
}
dfs1(node, node);
set<int> has, need;
need.insert(id[node]);
int cur = 0;
bool valid = true;
int hh;
while(!need.empty() && valid){
auto it = need.begin();
cur ++ ;
for(auto x : Z[(*it)]){
if(!now[x]){ // big optimization
valid=false;
break;
}
}
if(!valid) break;
for(auto x : Z[(*it)]){
hh = x;
while(hh != node){
hh=fin(hh);
if(!need.count(id[hh]) && !has.count(id[hh])){
need.insert(id[hh]);
}
par[hh] = up[hh];
}
}
has.insert(*it);
need.erase(it);
}
if(valid){
res = min(res, cur);
}
for(auto q : mark){
now[q]=false;
par[q]=q;
}
ban[node]=true;
for(auto x : T[node]){
if(!ban[x])
decomp(x);
}
}
int main(){
fastIO;
int n, k;
cin >> n >> k;
for(int i =1; i <= n; i ++ )
par[i]=i;
res = k;
int u, v;
for(int i = 1; i < n; i ++ ){
cin >> u >> v;
T[u].push_back(v);
T[v].push_back(u);
}
for(int i = 1; i <= n; i ++ ){
cin >> id[i];
Z[id[i]].push_back(i);
}
decomp(1);
cout << res - 1;
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3035 ms |
9728 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3035 ms |
9728 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3033 ms |
39388 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
3035 ms |
9728 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |