【題解】Codeforces 1387B1. Village (Minimum)

【題目敘述】http://codeforces.com/contest/1387/problem/B1

#include <iostream>
#include <set>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
 
int n, a, b, cnt, ans[100005];
set <int> st[100005];
priority_queue <pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    for (int i = 1; i < n; i++){
        cin >> a >> b;
        st[a].insert(b);
        st[b].insert(a);
    }
    for (int i = 1; i <= n; i++){
        if (st[i].size() == 1) pq.push({st[*st[i].begin()].size(), i});
    }
    while (!pq.empty()){
        int x = pq.top().second;
        pq.pop();
        if (st[x].empty()) continue;
        int y = *st[x].begin();
        int pre = y;
        for (auto i:st[y]){
            if (st[i].empty()) continue;
            st[i].erase(y);
            if (st[i].empty()){
                cnt += 2;
                ans[i] = pre;
                pre = i;
            }
            else if (st[i].size() == 1) pq.push({st[*st[i].begin()].size(), i});
        }
        ans[y] = pre;
        st[y].clear();
    }
    cout << cnt << "\n";
    for (int i = 1; i <= n; i++){
        cout << ans[i] << " ";
    }
    cout << "\n";
}
分享本文 Share with friends