Submission #678777

#TimeUsernameProblemLanguageResultExecution timeMemory
678777CyanmondPastiri (COI20_pastiri)C++17
100 / 100
845 ms67764 KiB
#include <bits/stdc++.h>

constexpr int inf = 100000000;

int main() {
    int N, K;
    std::cin >> N >> K;
    std::vector<int> A(N - 1), B(N - 1), O(K);
    std::vector<std::vector<int>> tree(N);
    for (int i = 0; i < N - 1; ++i) {
        std::cin >> A[i] >> B[i];
        --A[i], --B[i];
        tree[A[i]].push_back(B[i]);
        tree[B[i]].push_back(A[i]);
    }
    for (auto &e : O) {
        std::cin >> e;
        --e;
    }

    std::queue<int> que;
    std::vector<int> dist(N, -1);
    for (const int e : O) {
        que.push(e);
        dist[e] = 0;
    }
    while (not que.empty()) {
        const int f = que.front();
        que.pop();
        for (const int t : tree[f]) {
            if (dist[t] == -1) {
                dist[t] = dist[f] + 1;
                que.push(t);
            }
        }
    }

    std::vector<int> depth(N), ac(N);
    auto dfs = [&](auto &&self, const int v, const int p, const int d, int h) -> void {
        depth[v] = d;
        if (depth[v] + dist[v] > depth[h] + dist[h]) {
            h = v;
        }
        ac[v] = h;
        for (const int t : tree[v]) {
            if (t == p) {
                continue;
            }
            self(self, t, v, d + 1, h);
        }
    };
    dfs(dfs, 0, -1, 0, 0);

    std::sort(O.begin(), O.end(), [&](const int a, const int b) {
        return depth[a] > depth[b];
    });
    
    std::vector<bool> seen(N);
    std::vector<int> answer;
    for (int i = 0; i < K; ++i) {
        if (seen[O[i]]) {
            continue;
        }
        que.push(ac[O[i]]);
        seen[ac[O[i]]] = true;
        answer.push_back(ac[O[i]]);
        while (not que.empty()) {
            const int f = que.front();
            que.pop();
            for (const int t : tree[f]) {
                if (seen[t]) {
                    continue;
                }
                if (dist[t] + 1 == dist[f]) {
                    seen[t] = true;
                    que.push(t);
                }
            }
        }
    }

    std::sort(answer.begin(), answer.end());
    std::cout << answer.size() << std::endl;
    for (int i = 0; i < (int)answer.size(); ++i) {
        std::cout << answer[i] + 1;
        std::cout << (i == (int)answer.size() - 1 ? '\n' : ' ');
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...