結果
| 問題 |
No.364 門松木
|
| コンテスト | |
| ユーザー |
btk
|
| 提出日時 | 2016-05-19 23:52:33 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,146 bytes |
| コンパイル時間 | 2,320 ms |
| コンパイル使用メモリ | 185,336 KB |
| 実行使用メモリ | 24,576 KB |
| 最終ジャッジ日時 | 2024-10-06 11:06:04 |
| 合計ジャッジ時間 | 4,991 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 10 WA * 21 |
ソースコード
/*
* Problem link
*
*/
#include<bits/stdc++.h>
using namespace std;
struct INIT{INIT(){cin.tie(0);ios_base::sync_with_stdio(false);} }init;
typedef vector<int> V;
typedef vector<int> E;
typedef vector<E> Graph;
typedef long long LL;
#define rep(i,n) for (auto i = 0; i < n; i++)
#define range(it,v) for(auto &it:v)
void make_tree(int v, Graph &G, E &P,Graph &C) {
range(to, G[v]) {
if (to != P[v]) {
C[v].push_back(to);
P[to] = v;
make_tree(to, G, P, C);
}
}
}
int main() {
#ifdef INPUT_FROM_FILE
ifstream cin("sample.in");
ofstream cout("sample.out");
#endif
int N;
while (cin >> N) {
V val(N + 1), par(N, -1);
rep(i, N)cin >> val[i];
val[N] = 0;
Graph G(N), child(N);
rep(i, N - 1) {
int x, y;
cin >> x >> y; x--, y--;
G[x].push_back(y);
G[y].push_back(x);
}
par[0] = N;
make_tree(0, G, par, child);
//自ノードより小さい葉ノードのみ(親含む
vector<LL> dp_small(N, 0);
//自ノードより小さい葉ノードのみ(親なし
vector<LL> dp_small_p(N, 0);
//自ノードより大きい葉ノードのみ(親含む
vector<LL> dp_large(N, 0);
//自ノードより大きい葉ノードのみ(親なし
vector<LL> dp_large_p(N, 0);
LL res = 0ll;
std::function<void(int)> dfs = [&](int v) {
map<int, LL> l, s;
range(u, child[v]) {
dfs(u);
int x = val[u];
if (x < val[v])
l[x] = max(l[x], dp_large_p[u]);
if (x > val[v])
s[x] = max(s[x], dp_small_p[u]);
}
LL l_sum = 0, s_sum = 0;
LL ln = (LL)l.size();
LL sn = (LL)s.size();
range(it, l)l_sum += it.second;
range(it, s)s_sum += it.second;
dp_small[v] = l_sum + (ln)*(ln - 1) / 2;
dp_large[v] = s_sum + (sn)*(sn - 1) / 2;
if (l.count(val[par[v]]))l_sum -= l[val[par[v]]], ln--;
if (s.count(val[par[v]]))l_sum -= s[val[par[v]]], sn--;
dp_small_p[v] = l_sum + (ln)*(ln + 1) / 2;
dp_large_p[v] = s_sum + (sn)*(sn + 1) / 2;
};
dfs(0);
rep(i, N) {
res = max(res, dp_large[i]);
res = max(res, dp_small[i]);
if (i) {
res = max(res, dp_large_p[i]);
res = max(res, dp_small_p[i]);
}
}
cout << res << endl;
}
return 0;
}
btk