結果
問題 |
No.1484 木に数を書き込む問題 / Just Write Numbers! 2
|
ユーザー |
![]() |
提出日時 | 2021-04-08 13:11:40 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 238 ms / 2,000 ms |
コード長 | 1,582 bytes |
コンパイル時間 | 1,999 ms |
コンパイル使用メモリ | 199,124 KB |
最終ジャッジ日時 | 2025-01-20 13:05:54 |
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
#include <bits/stdc++.h> #define rep(i,n) for(int i = 0; i < (int)(n); i++) using namespace std; using LL = long long; using P = pair<int,int>; using vv = vector<vector<int>>; const int INF = (int)1e9; const LL LINF = (LL)1e18; const int Max_N = (int)2e5; class UnionFind { public: vector <long long> par; vector <long long> siz; UnionFind(long long sz_): par(sz_), siz(sz_, (long long)1) { for (long long i = 0; i < sz_; ++i) par[i] = i; } void init(long long sz_) { par.resize(sz_); siz.assign(sz_, (long long)1); for (long long i = 0; i < sz_; ++i) par[i] = i; } long long root(long long x) { while (par[x] != x) { x = par[x] = par[par[x]]; } return x; } bool unite(long long x, long long y) { x = root(x); y = root(y); if (x == y) return false; if (siz[x] < siz[y]) swap(x, y); siz[x] += siz[y]; par[y] = x; return true; } bool same(long long x, long long y) { return root(x) == root(y); } long long size(long long x) { return siz[root(x)]; } }; vv G; int depth = 0, f = 0; void dfs(int n, int d = 0, int par = -1){ if(d >= depth){ depth = d; f = n; } for(auto v : G[n]){ if(v == par) continue; dfs(v, d + 1, n); } } int main(){ int N; cin >> N; assert(2 <= N and N <= Max_N); UnionFind uf(N); G.resize(N); rep(i,N-1){ int a, b; cin >> a >> b; assert(1 <= a and a < b and b <= N); a--; b--; G[a].emplace_back(b); G[b].emplace_back(a); uf.unite(a, b); } int r = 0; rep(i,N) if(uf.root(i) == i) r++; assert(r == 1); dfs(0); dfs(f); cout << (N - 1) * 2 - depth << endl; return 0; }