제출 #855242

#제출 시각아이디문제언어결과실행 시간메모리
855242NeroZeinNetwork (BOI15_net)C++17
18 / 100
7 ms27228 KiB
#include "bits/stdc++.h" using namespace std; #ifdef Nero #include "Deb.h" #else #define deb(...) #endif const int N = 5e5 + 5; int a, b; int pr[N]; int dep[N]; vector<int> g[N]; vector<int> vec[N]; bool from_diameter[N]; vector<pair<int,int>> ans; int dfs(int v, int p) { int ret = v; for (int u : g[v]) { if (u != p) { pr[u] = v; dep[u] = dep[v] + 1; int t = dfs(u, v); if (dep[t] > dep[ret]) { ret = t; } } } return ret; } vector<int> merge(vector<int>& x, vector<int>& y) { if (x.size() < y.size()) swap(x, y); for (int v : y) x.push_back(v); return x; } vector<int> extract(vector<int>& x, vector<int>& y) { if (x.size() < y.size()) swap(x, y); for (int i = 0; i < (int) y.size(); ++i) { ans.emplace_back(x.back(), y.back()); y.pop_back(); x.pop_back(); } return x; } void dfs2(int v, int p) { if ((int) g[v].size() == 1 && v != a && v != b) { vec[v].push_back(v); } for (int u : g[v]) { if (u == p) { continue; } dfs2(u, v); if (!from_diameter[v]) { vec[v] = merge(vec[v], vec[u]); } else { vec[v] = extract(vec[v], vec[u]); } } } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for(int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } a = dfs(1, 1); dep[a] = 0; b = dfs(a, a); int x = b; while (true) { from_diameter[x] = true; if (x == a) { break; } x = pr[x]; } dfs2(a, a); ans.emplace_back(a, b); for (int v : vec[a]) { ans.emplace_back(a, v); } cout << (int) ans.size() << '\n'; for (auto [u, v] : ans) { cout << u << ' ' << v << '\n'; } return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...