Submission #927450

#TimeUsernameProblemLanguageResultExecution timeMemory
927450RegulusNetwork (BOI15_net)C++17
63 / 100
2090 ms57464 KiB
#include <bits/stdc++.h> #define IO ios::sync_with_stdio(false);cin.tie(0); #define debug(x) cerr << #x << " = " << (x) << ' ' #define bug(x) cerr << (x) << ' ' #define endl cerr << '\n' #define all(v) (v).begin(), (v).end() #define SZ(v) (ll)(v).size() #define lowbit(x) (x)&-(x) #define pb emplace_back #define F first #define S second using namespace std; using ll = long long; using pll = pair<ll, ll>; const int N = 5e5+5; int n, dis[N], fa[N], dsu[N]; pll e[N]; vector<int> g[N]; vector<pll> v2; inline int query(int x) { return (dsu[x]<0)?x : dsu[x]=query(dsu[x]); } inline bool unite(int x, int y) { x = query(x), y = query(y); if (x == y) return 0; dsu[y] = x; return 1; } inline void dfs(int x, int pre) { dis[x] = dis[pre] + 1, fa[x] = pre; for (int v : g[x]) if (v != pre) dfs(v, x); } inline pll find_dis() { int pos = query(1), pos2; dfs(pos, 0); for (int i=1; i <= n; ++i) if (dsu[i] == -1 && dis[i] > dis[pos]) pos = i; dfs(pos, 0), pos2 = pos; for (int i=1; i <= n; ++i) if (dsu[i] == -1 && dis[i] > dis[pos2]) pos2 = i; return {pos, pos2}; } int main(void) { IO int i, x, y; cin >> n; for (i=1; i <= n-1; ++i) cin >> x >> y, e[i] = {x, y}; int cnt = n; for (i=1; i <= n; ++i) dsu[i] = -1; while (cnt > 1) { //debug(cnt), endl; for (i=1; i <= n; ++i) g[i].clear(); for (i=1; i <= n-1; ++i) { x = query(e[i].F), y = query(e[i].S); //if (x != y) debug(x), debug(y), endl; if (x != y) g[x].pb(y), g[y].pb(x); } for (i=1; i <= n; ++i) { if (SZ(g[i]) == cnt-1) { for (int j=1; j < SZ(g[i]); j+=2) v2.pb(g[i][j-1], g[i][j]); if (SZ(g[i]) & 1) v2.pb(i, g[i].back()); break; } } if (i <= n) break; auto tp = find_dis(); v2.pb(tp.F, tp.S); int cur = tp.S; do { if (fa[cur]) cnt -= unite(cur, fa[cur]); cur = fa[cur]; } while (cur); //debug(dis[tp.S]-1), debug(cnt), endl; //for (i=1; i <= n; ++i) bug(query(i)); endl; } cout << SZ(v2) << '\n'; for (auto p : v2) cout << p.F << ' ' << p.S << '\n'; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...