結果

問題 No.1484 木に数を書き込む問題 / Just Write Numbers! 2
ユーザー 👑 platinumplatinum
提出日時 2021-04-08 13:11:40
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 212 ms / 2,000 ms
コード長 1,582 bytes
コンパイル時間 2,219 ms
コンパイル使用メモリ 205,320 KB
実行使用メモリ 26,412 KB
最終ジャッジ日時 2023-09-05 21:37:15
合計ジャッジ時間 8,833 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 4 ms
4,376 KB
testcase_05 AC 12 ms
4,376 KB
testcase_06 AC 14 ms
4,400 KB
testcase_07 AC 8 ms
4,376 KB
testcase_08 AC 16 ms
4,524 KB
testcase_09 AC 14 ms
4,376 KB
testcase_10 AC 13 ms
4,496 KB
testcase_11 AC 12 ms
4,376 KB
testcase_12 AC 10 ms
4,500 KB
testcase_13 AC 2 ms
4,380 KB
testcase_14 AC 157 ms
14,264 KB
testcase_15 AC 149 ms
13,780 KB
testcase_16 AC 128 ms
13,168 KB
testcase_17 AC 87 ms
10,720 KB
testcase_18 AC 157 ms
15,472 KB
testcase_19 AC 192 ms
17,148 KB
testcase_20 AC 208 ms
17,324 KB
testcase_21 AC 212 ms
17,184 KB
testcase_22 AC 199 ms
17,148 KB
testcase_23 AC 203 ms
17,292 KB
testcase_24 AC 202 ms
17,168 KB
testcase_25 AC 206 ms
17,212 KB
testcase_26 AC 202 ms
17,264 KB
testcase_27 AC 202 ms
17,324 KB
testcase_28 AC 200 ms
17,352 KB
testcase_29 AC 152 ms
26,412 KB
testcase_30 AC 156 ms
20,868 KB
testcase_31 AC 109 ms
18,096 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#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;
}
0