Submission #544482

#TimeUsernameProblemLanguageResultExecution timeMemory
544482inventiontimeNetwork (BOI15_net)C++17
0 / 100
8 ms11988 KiB
#include <bits/stdc++.h>
using namespace std;

#define int ll
#define endl '\n'

#define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb push_back
#define re resize
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define loop(i, n) for(int i = 0; i < n; i++)
#define loop1(i, n) for(int i = 1; i <= n; i++)
#define print(x) cout << #x << ": " << x << endl

typedef long long ll;
typedef vector<int> vi;
typedef array<int, 2> ii;
typedef array<int, 3> ti;
typedef vector<ii> vii;
typedef vector<ti> vti;
typedef priority_queue<int> pq;

template<class T> bool ckmin(T&a, T b) { bool B = a > b; a = min(a, b); return B; }
template<class T> bool ckmax(T&a, T b) { bool B = a < b; a = max(a, b); return B; }

const int inf = 1e17;
const int maxn = 5e5+5;

vi adj[maxn];

int leaves;
int sub[maxn];
int node;

void dfs(int u, int p) {

    int maxs = 0;
    for(auto v : adj[u]) if(v != p) {
        dfs(v, u);
        sub[u] += sub[v];   
        ckmax(maxs, sub[v]);
    }

    ckmax(maxs, leaves - sub[u]);
    if(maxs <= (leaves + 1)/2) node = u;

}

void solve_sub(int u, int p, vi& a) {

    for(auto v : adj[u]) if(v != p)
        solve_sub(v, u, a);

    if(adj[u].size() == 1) a.pb(u);

}

void result(int u) {

    vi a, b;

    for(auto v : adj[u]) {
        solve_sub(v, u, a);
        while(!a.empty() and !b.empty()) {
            int x = a.back(); a.pop_back();
            int y = b.back(); b.pop_back();
            cout << x << " " << y << endl;
        }
        if(!a.empty()) swap(a, b);
    }

    for(auto v : b) {
        cout << v << " " << node << endl;
    }

}

void solve() {
    
    int n; cin >> n;
    loop1(i, n-1) {
        int u, v;
        cin >> u >> v;
        adj[u].pb(v);
        adj[v].pb(u);
    }

    loop1(i, n) sub[i] = 0;

    leaves = 0;
    loop1(i, n) if(adj[i].size() == 1) {
        sub[i] = 1;
        leaves++;
    }

    dfs(1, 1);
    cout << (leaves + 1) / 2 << endl;
    result(node);

}

signed main() {

    fast_io;

    int t = 1; //cin >> t;
    while(t--)
        solve();

    cout << flush;

    return 0;

}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...