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 mp make_pair
#define ll long long
#define migmig cin.tie(NULL);ios_base::sync_with_stdio(false)
#define max_heap(T) priority_queue<T>
#define min_heap(T) priority_queue<T, vector<T>, greater<T>>
#define pb push_back
#define fi first
#define sec second
#define endl "\n"
#define pii pair <int, int>
using namespace std;
const ll MOD = 1e9 + 7;
const int INF = 1e9 + 1;
const ll INF18 = 1e18 + 1;
const int MAXN = 2e5 + 1;
const int LOG = 23;
int dp[MAXN][300];
vector <int> adj[MAXN];
int h[MAXN];
int maax, maxy;
int par[MAXN];
bool visited[MAXN];
int d;
int dp2[MAXN][300];
int be[MAXN];
void dfs(int r){
for (int i : adj[r]){
if (par[r] == i) continue;
dfs(i);
for (int j = 1; j <= d; j++) dp2[r][j] += dp[i][j - 1];
}
for (int i : adj[r]){
if (par[r] == i) continue;
for (int j = 1; j <= d / 2; j++){
dp[r][j] = max(dp[r][j], dp2[r][d - j] - dp[i][d - j - 1] + dp[i][j - 1]);
}
}
for (int j = d / 2 + 1; j <= d; j++) dp[r][j] = dp2[r][j];
dp[r][0] = dp2[r][d] + 1;
for (int j = d - 1; j >= 0; j--) dp[r][j] = max(dp[r][j], dp[r][j + 1]);
}
void dfs2(int r){
visited[r] = 1;
if (be[r] && h[r] > maax) maax = h[r], maxy = r;
for (int i : adj[r]){
if (visited[i] == 1) continue;
h[i] = h[r] + 1;
dfs2(i);
}
}
void solve(){
int n;
cin >> n >> d;
for (int i = 1; i < n; i++){
int u;
cin >> u;
par[i] = u;
adj[u].pb(i);
adj[i].pb(u);
}
d = min(n, d);
if (d < 300){
dfs(0);
cout << dp[0][0] << endl;
}
else{
int num = 0;
int v = 0;
for (int i = 0; i < n; i++) be[i] = 1;
while(1){
h[v] = 0, maax = -1;
memset(visited, 0, sizeof(visited));
dfs2(v);
int u = maxy;
h[u] = 0, maax = -1;
memset(visited, 0, sizeof(visited));
dfs2(u);
num++;
for (int i = 0; i < n; i++){
if (be[i] && h[i] < d){
be[i] = 0;
if (v == i) v = -1;
}
else if (be[i] && v == -1) v = i;
}
if (v == -1) break;
}
cout << num << endl;
}
}
int main(){
migmig;
int tc = 1;
// cin >> tc;
for (int ti = 0; ti < tc; ti++) solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |