結果
| 問題 | No.1154 シュークリームゲーム(Hard) |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2026-04-27 19:44:17 |
| 言語 | C++23 (gcc 15.2.0 + boost 1.89.0) |
| 結果 |
AC
|
| 実行時間 | 2 ms / 2,000 ms |
| コード長 | 2,146 bytes |
| 記録 | |
| コンパイル時間 | 2,575 ms |
| コンパイル使用メモリ | 348,196 KB |
| 実行使用メモリ | 6,400 KB |
| 最終ジャッジ日時 | 2026-04-27 19:44:29 |
| 合計ジャッジ時間 | 4,076 ms |
|
ジャッジサーバーID (参考情報) |
judge1_0 / judge3_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 40 |
ソースコード
//#define _GLIBCXX_DEBUG
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0; i<(n); i++)
#define rng(i,l,r) for(int i=(l); i<(r); i++)
#define rrep(i,n) for(int i=(n)-1; i>=0; i--)
#define each(i,x) for(auto i:x)
#define all(x) x.begin(),x.end()
using ll=long long;
#define fi first
#define se second
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;cin>>n;
vector<ll> a(n);
rep(i,n)cin>>a[i];
ll sa=0;
each(i,a)sa+=i;
vector<vector<int>> tree(n);
rep(i,n-1){
int u,v;cin>>u>>v;
tree[u-1].push_back(v-1);
tree[v-1].push_back(u-1);
}
vector<int> order={0};
vector<int> par(n,-2);
par[0]=-1;
rep(i,n){
int p=order[i];
each(j,tree[p]){
if(par[j]==-2){
par[j]=p;
order.push_back(j);
}
}
}
reverse(all(order));
vector<priority_queue<ll>> pq(n);
ll ans=0;
each(i,order){
pair<int,int> mx={-1,-1};
each(j,tree[i]){
if(par[i]==j)continue;
mx=max(mx,{pq[j].size(),j});
}
if(mx.se!=-1){
swap(pq[mx.se],pq[i]);
}
each(j,tree[i]){
if(par[i]==j||j==mx.se)continue;
while(!pq[j].empty()){
pq[i].push(pq[j].top());
pq[j].pop();
}
}
bool flg=true;
while(!pq[i].empty()&&pq[i].top()>a[i]){
if(pq[i].size()==1){
flg=false;
if(n%2==1){
ans-=a[i];
ans+=pq[i].top();
}
else{
ans+=a[i];
ans-=pq[i].top();
}
pq[i].pop();
}
else{
a[i]-=pq[i].top();
pq[i].pop();
a[i]+=pq[i].top();
pq[i].pop();
}
}
if(flg)pq[i].push(a[i]);
}
int sign=1;
while(!pq[0].empty()){
ans+=sign*pq[0].top();
pq[0].pop();
sign*=-1;
}
cout<<ans<<"\n";
}