Submission #1335568

#TimeUsernameProblemLanguageResultExecution timeMemory
1335568niwradHard route (IZhO17_road)C++20
0 / 100
1 ms344 KiB
#include <algorithm>
#include <bits/stdc++.h>
#include <functional>
using namespace std;
int n, k;

vector<vector<int>> graph;
vector<vector<pair<int, int>>> child_len;
int mn;

int pull_up(int node, int par) {
    for (auto next : graph[node]) {
        if (next != par) {
            child_len[node].push_back({pull_up(next, node), next});
        }
    }
    sort(child_len[node].begin(), child_len[node].end(), greater<pair<int, int>>());
    int mx = 0;
    if (child_len[node].size()) {
        mx = child_len[node][0].first;
    }
    return mx + 1;
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> k;
    graph.resize(n); child_len.resize(n);
    for (int i = 0; i < n - 1; i++) {
        int a, b;
        cin >> a >> b;
        graph[--a].push_back(--b);
        graph[b].push_back(a);
    }
    mn = 2 * n - 2;
    pull_up(0, -1);
    if (k == 1) {
        for (int i = 0; i < n; i++) {
            if (child_len[i].size() > 1) {
                mn = min(mn, 2 * n - 2 - child_len[i][0].first - child_len[i][1].first);
            } else if (child_len[i].size()) {
                mn = min(mn, 2 * n - 2 - child_len[i][0].first + 1);
            }
        }
        cout << mn << "\n";
    } else {
        cout << "-1";
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...