Submission #870591

#TimeUsernameProblemLanguageResultExecution timeMemory
870591sleepntsheepCat in a tree (BOI17_catinatree)C++17
100 / 100
104 ms55636 KiB
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <deque>
#include <set>
#include <utility>
#include <array>
#include <cassert>

using namespace std;
#define ALL(x) x.begin(), x.end()
#define ShinLena cin.tie(nullptr)->sync_with_stdio(false);
using i64 = long long;
#define N (1<<20)

int n, d, t[N];
vector<int> g[N];
array<int, 2> dp[N];

void upd(int p, int k) {;for (; p ; p-=p&-p) t[p] += k; }
int qry(int p) { ; int z = 0; for (; p < N; p+=p&-p) z += t[p]; return z; }

void dfs(int u, int p, int dep)
{
    int base = 0;

    for (auto v : g[u]) if (v != p) dfs(v, u, dep+1), base += dp[v][0] - 1;


    vector<int> dm;
    for (auto v : g[u]) if (v != p) upd(dp[v][1], 1), dm.push_back(dp[v][1]);
    sort(ALL(dm));

    dp[u] = {base + 1 + qry(d + dep), dep};

    for (auto v : g[u]) if (v != p)
    {
        upd(dp[v][1], -1);
        if (dp[v][1] < dep + (d+1)/2)
            dp[u] = max(dp[u], {base + 1 + qry(dep + max((d+1)/2, d - (dp[v][1] - dep))), dp[v][1]});
        else
        {
            int D = *lower_bound(ALL(dm), dep + (d+1)/2);
            dp[u] = max(dp[u], {base + 1 + qry(dep + max((d+1)/2, d - (dp[v][1] - dep))), D});
        }
        upd(dp[v][1], 1);
    }

    for (auto v : g[u]) if (v != p) upd(dp[v][1], -1);
}

int main()
{
    ShinLena;
    cin >> n >> d;
    for (int i = 1, v; i < n; ++i) cin >> v, g[i].push_back(v), g[v].push_back(i);
    dfs(0, 0, 1);
    cout << dp[0][0];

    return 0;
}


#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...