結果
問題 | No.364 門松木 |
ユーザー |
![]() |
提出日時 | 2016-05-20 00:07:58 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 44 ms / 3,000 ms |
コード長 | 2,257 bytes |
コンパイル時間 | 1,873 ms |
コンパイル使用メモリ | 185,852 KB |
実行使用メモリ | 24,704 KB |
最終ジャッジ日時 | 2024-10-11 01:03:20 |
合計ジャッジ時間 | 4,600 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 31 |
ソースコード
/** 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_FILEifstream cin("sample.in");ofstream cout("sample.out");#endifint 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_small_p[u]);if (x < val[v])s[x] = max(s[x], dp_large_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_large[v] = l_sum + (ln)*(ln - 1) / 2;dp_small[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]]))s_sum -= s[val[par[v]]], sn--;if (val[par[v]] > val[v])ln++;if (val[par[v]] < val[v])sn++;if (val[par[v]] != val[v]) {dp_large_p[v] = l_sum + (ln)*(ln - 1) / 2;dp_small_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;}