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 f first
#define s second
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pb push_back
#define epb emplace_back
using namespace std;
const int nmax = 2e5 + 1;
vector <vector <pii> > cent(nmax);
vector <bool> marked(nmax);
vector <int> sz(nmax);
vector <int> mx(nmax);
vector <vector <int> > g(nmax);
vector <int> cur(nmax, 1e9);
void dfs(int v, int e = -1){
sz[v] = 1;
mx[v] = 0;
for(int to : g[v]){
if(marked[to]) continue;
if(to == e) continue;
dfs(to, v);
sz[v] += sz[to];
mx[v] = max(mx[v], sz[to]);
}
}
int find_cen(int v, int s, int e = -1){
if(mx[v] <= s / 2){
if(sz[v] >= s / 2) return v;
}
for(int to : g[v]){
if(to == e || marked[to]) continue;
int x = find_cen(to, s, v);
if(x != -1) return x;
}
return -1;
}
void DFS(int v, int d, int st, int e = -1){
cent[v].pb({d, st});
for(int to : g[v]){
if(to == e || marked[to]) continue;
DFS(to, d + 1, st, v);
}
}
void rec(int v){
dfs(v);
int x = find_cen(v, sz[v]);
DFS(x, 0, x);
marked[x] = true;
for(int to : g[x]){
if(!marked[to])
rec(to);
}
}
int getmn(int v){
int ans = 1e9;
for(auto cc : cent[v]){
int x = cc.s, y = cc.f;
ans = min(ans, cur[x] + y);
}
return ans;
}
void mark(int v){
for(auto cc : cent[v]){
int x = cc.s, y = cc.f;
cur[x] = min(cur[x], y);
}
}
vector <pii> vv;
void stupidguy(int v, int d, int e = -1){
vv.pb({d, v});
for(int to : g[v]){
if(to == e) continue;
stupidguy(to, d + 1, v);
}
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
int n; cin >> n;
int D; cin >> D;
for(int i = 1; i < n; i++){
int x; cin >> x;
g[x].pb(i);
g[i].pb(x);
}
rec(1);
int ans = 0;
stupidguy(1, 0);
sort(vv.begin(), vv.end());
for(int i = vv.size() - 1; i >= 0; i--){
int x = vv[i].s;
if(getmn(x) >= D){
ans++;
mark(x);
}
}
cout << ans;
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... |