結果

問題 No.364 門松木
コンテスト
ユーザー ryofjt
提出日時 2016-09-12 18:17:47
言語 C++11(old_compat)
(gcc 12.4.0 + boost 1.89.0)
コンパイル:
g++-12 -O2 -lm -std=gnu++11 -Wuninitialized -DONLINE_JUDGE -include bits/stdc++.h -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 418 ms / 3,000 ms
コード長 1,173 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,939 ms
コンパイル使用メモリ 173,064 KB
実行使用メモリ 311,936 KB
最終ジャッジ日時 2026-03-08 16:07:38
合計ジャッジ時間 9,679 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 31
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <iostream>
#include <algorithm>

#define rep(i, n) for(int i = 0; i < (n); ++i)

using namespace std;

typedef unsigned int uint;
typedef vector<int> V;
typedef vector<short> VS;
typedef vector<uint> VU;

int n;
int a[50000];
V t[50000];
bool u[50000];
uint ans;

VU eval(const VS& c, const VU& v, int p){
	V cs(1000 + 1, 0);
	VU vs(1000 + 1, 0);
	rep(i, 1000){
		cs[i + 1] = cs[i] + c[i];
		vs[i + 1] = vs[i] + v[i];
	}
	uint ca = cs[p], va = vs[p];
	uint cb = cs[1000] - cs[p + 1], vb = vs[1000] - vs[p + 1];
	uint vc = vs[p + 1] - vs[p];
	return {ca * (ca - 1) / 2 + va, cb * (cb - 1) / 2 + vb, vc};
}

uint dfs(int x, int k){
	u[x] = true;
	VS c(1000, 0);
	VU v(1000, 0);
	for(int i: t[x]){
		if(!u[i]){
			c[a[i]] = 1;
			v[a[i]] = max(dfs(i, a[x]), v[a[i]]);
		}
	}
	auto e1 = eval(c, v, a[x]);
	ans = max(*max_element(e1.begin(), e1.end()), ans);
	c[k] = 1;
	v[k] = 0;
	auto e2 = eval(c, v, a[x]);
	return x[a] != k ? e2[x[a] < k] : e2[2];
}

int main(){
	cin >> n;
	rep(i, n){
		cin >> a[i];
		--a[i];
	}
	rep(i, n - 1){
		int x, y;
		cin >> x >> y;
		--x;
		--y;
		t[x].push_back(y);
		t[y].push_back(x);
	}

	dfs(0, 1);
	cout << ans << endl;
	return 0;
}
0