Submission #156015

# Submission time Handle Problem Language Result Execution time Memory
156015 2019-10-02T15:06:55 Z DS007 Torrent (COI16_torrent) C++14
100 / 100
537 ms 25904 KB
#include <bits/stdc++.h>
using namespace std;

const int mn = 300005;
vector<int> adj[mn];
vector<int> path;
int n, a, b, u, v;

bool find(int x, int p = -1) {
    if (x == b) {
        path.push_back(b);
        return true;
    }

    for (int i : adj[x]) {
        if (i != p && find(i, x)) {
            path.push_back(x);
            return true;
        }
    }

    return false;
}

int dfs(int x, int p = -1) {
    vector<int> s;
    int c = 0;

    for (int i : adj[x]) {
        if ((i == u && x == v) || (i == v && x == u) || i == p)
            continue;
        c++;
        s.push_back(dfs(i, x));
    }

    sort(s.begin(), s.end(), greater<>());

    int ans = 0;
    for (int i = 0, l = s.size(); i < l; i++)
        ans = max(ans, s[i] + i);

    return ans + 1;
}

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

    cin >> n >> a >> b;
    a--, b--;

    for (int i = 0; i < n - 1; i++) {
        int x, y;
        cin >> x >> y;
        x--, y--;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    find(a);
    reverse(path.begin(), path.end());

    int l = 1, h = path.size() - 1, m = -1, ans = 1e9;
    while (l <= h) {
        m = (l + h) / 2;
        u = path[m - 1], v = path[m];
        int v1 = dfs(a), v2 = dfs(b);
        ans = min(ans, max(v1, v2) - 1);
        if (v1 < v2)
            l = m + 1;
        else
            h = m - 1;
    }

    if (m > 1) {
        u = path[m - 2], v = path[m - 1];
        ans = min(ans, max(dfs(a), dfs(b)) - 1);
    }

    cout << ans;
}
# Verdict Execution time Memory Grader output
1 Correct 9 ms 7416 KB Output is correct
2 Correct 9 ms 7416 KB Output is correct
3 Correct 9 ms 7416 KB Output is correct
# Verdict Execution time Memory Grader output
1 Correct 537 ms 23020 KB Output is correct
2 Correct 507 ms 24440 KB Output is correct
3 Correct 463 ms 25640 KB Output is correct
4 Correct 530 ms 25004 KB Output is correct
5 Correct 526 ms 22608 KB Output is correct
6 Correct 484 ms 23160 KB Output is correct
7 Correct 486 ms 25904 KB Output is correct