제출 #1241713

#제출 시각아이디문제언어결과실행 시간메모리
1241713knhatdevMousetrap (CEOI17_mousetrap)C++20
0 / 100
155 ms59112 KiB

#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1e6;
bool onPathTM[MAX_N + 1];
int parent[MAX_N + 1];
int dpArb[MAX_N + 1];
vector<int> adj[MAX_N + 1];

void dfs(int u, int p) {
    parent[u] = p;
    for (int v: adj[u]) {
        if (v == p)
            continue;
        dfs(v, u);
    }
}

void calcDp(int u, int p) {
    int max1 = 0, max2 = 0;
    int sons = 0;
    for (int v: adj[u]) {
        if (v == p)
            continue;
        

        if (!onPathTM[v]) {
          calcDp(v, u);
            if (dpArb[v] > max1) {
                max2 = max1;
                max1 = dpArb[v];
            } else if (dpArb[v] > max2) 
                max2 = dpArb[v];
            sons++;
        }
    }

    dpArb[u] = sons + max2;

    // printf("%d %d\n", u, dp[u]);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, t, m;

    cin >> n >> t >> m;
    for (int e = 0; e < n - 1; e++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    dfs(t, 0);

    int w = m;
    vector<int> path;
    while (w != t) {
        onPathTM[w] = true;
        path.push_back(w);
        w = parent[w];
    }
    onPathTM[w] = true;

    int totalSons = 0;
    for (int u: path) {
        for (int v: adj[u]) {
            if (onPathTM[v])
                continue;
            totalSons++;
        }
    }

    calcDp(t, 0);

    int l = -1, r = n;
    while (r - l > 1) {
        int mid = (l + r) / 2;

        int b = 0, remSons = totalSons;
        int a = 0; 
        bool ok = true;
        for (int u: path) {
            b++;
            int crtSons = 0, aa = 0;
            for (int v: adj[u]) { 
                if (onPathTM[v])
                    continue;

                // printf("%d %d %d\n", dpArb[v], remSons, a);
                if (dpArb[v] + remSons + a > mid) {
                    b--;
                    aa++;
                    if (b < 0)
                        ok = false;
                }
                crtSons++;
            }
            remSons -= crtSons;
            a += aa;
        }
        if (a > mid)
            ok = false;

        // printf("%d %d\n", mid, ok);
        if (ok)
            r = mid;
        else
            l = mid;
    }

    cout << r << "\n";

    return 0;
}   

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