제출 #870340

#제출 시각아이디문제언어결과실행 시간메모리
870340sleepntsheepCat in a tree (BOI17_catinatree)C++17
51 / 100
26 ms4960 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 200860

int n, d, h[N], alloc = 1, dp[N][2], t[N];
pair<int, int> g[N<<1];

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

void add_edge(int u, int v)
{
    g[alloc] = {v, h[u]}; h[u] = alloc++;
}

void dfs(int u, int p, int dep)
{
    int base = 0, safe = (d+1)/2, sel;

    for (auto j = h[u]; j; j = g[j].second) dfs(g[j].first, u, dep+1), base += dp[g[j].first][0] - 1;

    for (auto j = h[u]; j; j = g[j].second) upd(dp[g[j].first][1], 1);

    {
        int sel = base + 1 + qry(d + dep);
        if (dp[u][0] < sel) dp[u][0] = sel, dp[u][1] = dep;
        else if (dp[u][0] == sel && dep > dp[u][1]) dp[u][1] = dep;
    }

    for (auto j = h[u]; j; j = g[j].second)
    {
        int v = g[j].first;
        int delta = dp[v][1] - dep, subdep = dp[v][1];
        upd(dp[v][1], -1);
        sel = base + 1 + qry(dep + max(safe, d - delta));
        upd(dp[v][1], 1);
        if (dp[u][0] < sel) dp[u][0] = sel, dp[u][1] = subdep;
        else if (dp[u][0] == sel && subdep > dp[u][1]) dp[u][1] = subdep;
    }

    for (auto j = h[u]; j; j = g[j].second) upd(dp[g[j].first][1], -1);
}

int main()
{
    ShinLena;
    cin >> n >> d;
    for (int i = 1, v; i < n; ++i) cin >> v, add_edge(v, 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...