結果

問題 No.2654 [Cherry 6th Tune] Re: start! (Black Sheep)
ユーザー Kude
提出日時 2024-02-23 23:23:26
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 338 ms / 7,000 ms
コード長 2,261 bytes
コンパイル時間 4,119 ms
コンパイル使用メモリ 283,464 KB
実行使用メモリ 59,220 KB
最終ジャッジ日時 2024-09-29 08:55:22
合計ジャッジ時間 14,497 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

#include<bits/stdc++.h>
namespace {
#pragma GCC diagnostic ignored "-Wunused-function"
#include<atcoder/all>
#pragma GCC diagnostic warning "-Wunused-function"
using namespace std;
using namespace atcoder;
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--)
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
template<class T> bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; }
template<class T> bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; }
using ll = long long;
using P = pair<int,int>;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<ll>;
using VVL = vector<VL>;
} int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
n++;
VI a(n);
rep(i, n) cin >> a[i];
VVI to(n);
rep(i, n - 1) {
int u, v;
cin >> u >> v;
to[u].emplace_back(v);
to[v].emplace_back(u);
}
vector<int> ord(n);
iota(ord.begin(), ord.end(), 0);
sort(ord.begin(), ord.end(), [&](int i, int j) {
return a[i] < a[j];
});
VI pos(n);
rep(i, n) pos[ord[i]] = i;
segtree<int, [](int x, int y) { return x + y; }, []() { return 0; }> seg(n);
fenwick_tree<ll> ft(n);
VL ans(n);
auto dfs = [&](auto&& self, int u, int p, int d) -> void {
seg.set(pos[u], 1);
ft.add(pos[u], a[u]);
if (d >= 2) {
int l0 = seg.max_right(0, [&](int x) { return x <= 0; });
int l1 = seg.max_right(0, [&](int x) { return x <= 1; });
int r0 = seg.min_left(n, [&](int x) { return x <= 0; });
int r1 = seg.min_left(n, [&](int x) { return x <= 1; });
if (a[ord[l0]] == a[ord[r0 - 1]]) {
ans[u] = 1;
} else {
ans[u] = 4e18;
for (auto [l, r] : {pair(l0, r1), pair(l1, r0)}) {
int cnt = d + 1 - 1;
int c = seg.max_right(l, [&](int x) { return x <= cnt / 2; });
chmin(ans[u], ft.sum(c, r) - ft.sum(l, c) + (- ((cnt + 1) / 2) + cnt / 2) * a[ord[c]]);
}
}
} else {
ans[u] = -1;
}
for (int v : to[u]) if (v != p) self(self, v, u, d + 1);
ft.add(pos[u], -a[u]);
seg.set(pos[u], 0);
};
dfs(dfs, 0, -1, 0);
rep(i, n) if (i) cout << ans[i] << '\n';
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0