Monday, January 15, 2024

[Codeforces] F. Minimum Maximum Distance


Problem Link    : F. Minimum Maximum Distance
Category        : Approximate Problem
Contest         : Codeforces Round 903 (Div. 3) 
#include "bits/stdc++.h"
using namespace std;
#define int     long long int
#define endl    '\n'
 
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    cout.precision(12);
 
    bool FILEIO = true; string FILE = "in.txt";
    if (FILEIO and fopen(FILE.c_str(), "r")) {
        freopen(FILE.c_str(), "r", stdin);
    }
 
    int tc;
    cin >> tc;
    for (int tcase = 1; tcase <= tc; tcase++) {
        int n, k;
        cin >> n >> k;
        vector<int> colors(n + 1);
        for (int i = 0; i < k; i++) {
            int u;
            cin >> u;
            colors[u] = 1;
        }
        vector<vector<int>> graph(n + 1);
        for (int e = 1; e < n; e++) {
            int u, v;
            cin >> u >> v;
            graph[u].push_back(v);
            graph[v].push_back(u);
        }
        vector<int> in(n + 1, -1);
        function<void(int, int)> SolveIn = [&](int u, int p) {
            if (colors[u] == 1) {
                in[u] = 0;
            }
            for (int v : graph[u]) {
                if (v == p) {
                    continue;
                }
                SolveIn(v, u);
                if (~in[v]) {
                    in[u] = max(in[u], 1 + in[v]);
                }
            }
        };
        SolveIn(1, 0);
        vector<int> out(n + 1, -1);
        function<void(int, int)> SolveOut = [&](int u, int p) {
            if (colors[u]) {
                out[u] = max(out[u], 0ll);
            }
            int max1 = -1;
            int max2 = -1;
            for (int v : graph[u]) {
                if (v == p) {
                    continue;
                }
                if (in[v] > max1) {
                    max2 = max1;
                    max1 = in[v];
                } else if (in[v] > max2) {
                    max2 = max(max2, in[v]);
                }
            }
            for (int v : graph[u]) {
                if (v == p) {
                    continue;
                }
                int use = max1;
                if (in[v] == use) {
                    use = max2;
                }
                if (~use) {
                    out[v] = 2 + use;
                }
                if (~out[u]) {
                    out[v] = max(out[v], 1 + out[u]);
                }
                SolveOut(v, u);
            }
        };
        SolveOut(1, 0);
        int mini = INT_MAX;
        for (int i = 1; i <= n; i++) {
            mini = min({mini, max(in[i], out[i])});
        }
        if (mini == INT_MAX) {
            mini = 0;
        }
        cout << mini << endl;
    }
}
 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.