Submission #1265194

#TimeUsernameProblemLanguageResultExecution timeMemory
1265194rtriNetwork (BOI15_net)C++20
0 / 100
0 ms328 KiB
#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> adj;
vector<pair<int, int>> ans;

vector<bool> is_leaf;

pair<int, int> dfs(int u, int p = -1, int d = 0) {
  if (is_leaf[u] && p != -1) {
    return {d, u};
  }

  int bestd = -1, besti = -1;
  for (int v : adj[u])
    if (v != p) {
      auto [subd, subi] = dfs(v, u, d + 1);
      if (subd > bestd) {
        bestd = subd;
        besti = subi;
      }
    }

  return {bestd, besti};
}

vector<bool> vis;
int verify(int u, int fa, int fb, int p = -1) {
  if (p == fa && u == fb)
    return 0;
  if (u == fa && p == fb)
    return 0;
  if (vis[u])
    return 0;
  vis[u] = 1;

  int sz = 1;
  for (int v : adj[u])
    sz += verify(v, fa, fb, u);
  for (auto [a, b] : ans)
    if (u == a)
      sz += verify(b, fa, fb, u);
    else if (u == b)
      sz += verify(a, fa, fb, u);

  return sz;
}

int main() {
  int k;
  cin >> k;
  adj.resize(k);
  vector<pair<int, int>> edg;
  for (int i = 0; i < k - 1; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    adj[a].push_back(b);
    adj[b].push_back(a);
    edg.push_back({a, b});
  }

  vector<int> leafs;
  is_leaf.resize(k);
  for (int i = 0; i < k; i++)
    if (adj[i].size() <= 1) {
      leafs.push_back(i);
      is_leaf[i] = 1;
    }

  for (int i = 0; i < leafs.size() / 2; i++) {
    int best_dist = -1;
    int best_leaf = -1, best_other = -1;
    for (int leaf : leafs)
      if (is_leaf[leaf]) {
        auto [dist, other] = dfs(leaf);
        if (best_dist < dist) {
          best_dist = dist;
          best_leaf = leaf;
          best_other = other;
        }
      }

    is_leaf[best_leaf] = 0;
    is_leaf[best_other] = 0;
    ans.push_back({best_leaf, best_other});
  }

  if (leafs.size() % 2 == 1) {
    int extra_leaf = -1;
    int other_leaf = 0;
    for (int i = 0; i < leafs.size(); i++)
      if (is_leaf[leafs[i]])
        extra_leaf = leafs[i];
      else
        other_leaf = leafs[i];
    ans.push_back({other_leaf, extra_leaf});
  }

  cout << ans.size() << "\n";
  for (auto [a, b] : ans) {
    cout << a + 1 << " " << b + 1 << "\n";
  }

  // TODO: remove
  if (false) {
    for (auto [a, b] : edg) {
      vis.resize(k);
      fill(vis.begin(), vis.end(), false);
      if (verify(0, a, b) != k) {
        cerr << "BAD" << endl;
        return 1;
      }
    }
  }

  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...