This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// In the name of God
// Hope is last to die
#include <bits/stdc++.h>
using namespace std;
// #pragma GCC optimize("O3,unroll-loops")
// #pragma GCC target("avx2")
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define pb push_back
// #define int long long
#define S second
#define F first
#define mp make_pair
#define smax(x, y) (x) = max((x), (y))
#define smin(x, y) (x) = min((x), (y))
#define all(x) (x).begin(), (x).end()
const int maxn = 1e5 + 5;
const int inf = 1e9 + 7;
int n, k, a[maxn], sz[maxn], par[maxn], id[maxn];
vector<int> adj[maxn], vec[maxn];
bool mark[maxn], vis[maxn];
queue<int> q;
int get_sz(int v, int p = -1){
sz[v] = 1;
for(auto u: adj[v]){
if(u != p && !mark[u]) sz[v] += get_sz(u, v);
}
return sz[v];
}
int find(int v, int p, int s){
for(auto u: adj[v]){
if(u != p && !mark[u] && sz[u] * 2 > s) return find(u, v, s);
}
return v;
}
void dfs(int v, int p, int r){
vis[a[v]] = 0;
par[v] = p;
id[v] = r;
for(auto u: adj[v]){
if(u != p && !mark[u]) dfs(u, v, r);
}
}
int centroid_decompose(int v){
v = find(v, 0, get_sz(v));
dfs(v, v, v);
q.push(a[v]);
int ans = 0;
while(q.size()){
int c = q.front();
q.pop();
if(vis[c]) continue;
vis[c] = 1;
for(auto u: vec[c]){
if(id[u] != v){
ans = k;
break;
}
q.push(a[par[u]]);
}
ans++;
}
mark[v] = 1;
for(auto u: adj[v]) if(!mark[u]) smin(ans, centroid_decompose(u));
return ans;
}
int32_t main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> k;
for(int i = 0; i < n - 1; i++){
int u, v; cin >> u >> v;
adj[u].pb(v);
adj[v].pb(u);
}
for(int i = 1; i <= n; i++){
cin >> a[i];
vec[a[i]].pb(i);
}
cout << centroid_decompose(1) - 1 << '\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... |