3.1.1

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
2.3 kB
2
Indexable
Never
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <math.h>

using namespace std;
vector<vector<int>> s;
vector<int> d, was, ans, m;
int d1 = 0, d2 = 0;
int vv = -1, vv2 = -1;
void dfs(int v, int dd = 0, int c = -1) {
    was[v] = 1;
    d[v] = dd;
    int fl = 0;
    for (auto to : s[v]) {

        if (!was[to]) {
            fl = 1;
            if(v == 0)
                dfs(to, dd + 1, to);
            else
                dfs(to, dd + 1, c);
        }
        
    }
    if (fl == 0) {
        m[c] = max(m[c], dd);
        if (m[c] > d1) {
            if (vv != -1) {
                d2 = d1;
                vv2 = vv;
            }
            d1 = m[c];
            vv = c;
        }
        else if (m[c] > d2) {
            d2 = m[c];
            vv2 = c;
        }
    }
}
int mn = 0;
void dfs2(int v, int c = -1) {
    if (v == 1)
        int t = 0;
    was[v] = 1;
    if (c == -1)
        ans[v] = m[vv];
    else {
        if (c != vv && vv != -1)
            ans[v] = max(m[c] - d[v], d[v] + m[vv]);
        else if (vv != -1) {
            if(vv2 != -1)
                ans[v] = max(m[c] - d[v], d[v] + m[vv2]);
            else {
                ans[v] = max(m[c] - d[v], d[v]);
            }
        }
        else {
            ans[v] = max(m[c] - d[v], d[v]);
        }

    }
    if (mn == 0)
        mn = ans[v];
    else
        mn = min(mn, ans[v]);
    for (auto to : s[v]) {
        if (!was[to]) {
            if (v == 0)
                dfs2(to, to);
            else
                dfs2(to, c);
        }
    }
}

int main() {
    int n; cin >> n; 
    if (n == 1) {
        cout << "0 1 1";
        return 0;
    }
    s.resize(n);
    d.resize(n);
    was.resize(n);
    ans.resize(n);
    m.resize(n);
    for (int i = 0; i < n - 1; i++) {
        int e, r;
        cin >> e >> r;
        e--; r--;
        s[e].push_back(r);
        s[r].push_back(e);
    }
    dfs(0);
    was.clear();
    was.resize(n, 0);
    dfs2(0);
    cout << mn << " ";
    vector<int> a;
    for (int i = 0; i < n; i++) {
        if (ans[i] == mn)
            a.push_back(i + 1);
    }
    cout << a.size() << " ";
    for (auto i : a)
        cout << i << " ";
    
}
Leave a Comment