Preface
赛时卡常了,复杂度应该是对的,重交一遍过了。
Sol
中位数,不禁想到 NOI2026 经典好题,考虑二分答案。
对于二分到的阈值 (后文记为 ),要使得存在一种划分让和 连通块(记为 类)的数目大于和 的连通块(记为 类)数目。
于是我们记 为 子树下 类数目减去 类数目的值,显然要尽可能使它最大,保证它最大的同时,维护可能的最大剩余和,使得它向父节点转移时有可能有贡献。
同时我们考虑到切断的边必须是偶数,我们可以分开存状态, 为当前切断偶数边的最优决策, 为当前切断奇数边的最优决策。
然后转移是容易的(虽然笔者不知道为什么调了三个小时):
枚举 、 切断边数的奇偶性,存在合法转移就比较当前最优决策与新决策(以 为第一关键字,剩余最大和为第二关键字),然后转移就行(要切断 时,记得考虑 上的剩余和对 的影响)。
类似于树上背包,复杂度 ,加上二分,复杂度 , 为值域大小。
AC Code
#include <bits/stdc++.h>
#define zls rp++
#define ll long long
#define ull unsigned long long
using namespace std;
const ll inf=4e18;
const ll md=998244353;
namespace FastIO{
static const int B=1<<20;
static char inbuf[B];
static char *pin1=inbuf,*pin2=inbuf;
inline char getchar(){
if(pin1==pin2){
pin2=(pin1=inbuf)+fread(inbuf,1,B,stdin);
if(pin1==pin2)return EOF;
}
return *pin1++;
}
template<typename T>
inline bool read(T &x){
x=0;int f=1;char ch=getchar();
if(ch==EOF)return false;
while(ch<'0'||ch>'9'){
if(ch==EOF)return false;
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){x=x*10+(ch-'0');ch=getchar();}
x*=f;
return true;
}
}
using namespace FastIO;
struct node{
ll sum,ok;//ok:num(>=m)-num(<m)
bool save;
};
int n;
ll w[100005];
vector<int>e[100005];
node dp[100005][2];
node cmp(node a,node b){
if(!a.save)return b;
if(!b.save)return a;
if(a.ok!=b.ok)return a.ok>b.ok?a:b;
return a.sum>b.sum?a:b;
}
void dfs(int u,int fa,ll m){
dp[u][0]={w[u],0,1};
dp[u][1]={0,0,0};
for(int v:e[u]){
if(v==fa)continue;
dfs(v,u,m);
node nd[2]={{0,0,0},{0,0,0}};
for(int p=0;p<2;p++){
if(!dp[u][p].save)continue;
for(int q=0;q<2;q++){
if(!dp[v][q].save)continue;
node a=dp[u][p],b=dp[v][q];
nd[p^q]=cmp(nd[p^q],
{a.sum+b.sum,a.ok+b.ok,1});
nd[p^q^1]=cmp(nd[p^q^1],
{a.sum,a.ok+b.ok+(b.sum>=m?1:-1),1});
}
}
dp[u][0]=nd[0];
dp[u][1]=nd[1];
}
}
bool check(ll m){
dfs(1,0,m);
if(!dp[1][0].save)return 0;
ll ok=dp[1][0].ok;
if(dp[1][0].sum>=m)ok++;
else ok--;
return ok>0;
}
void work(){
read(n);
ll l=0,r=0;
for(int i=1;i<=n;i++){
e[i].clear();
read(w[i]);
l+=w[i];
r+=(w[i]>0?w[i]:0);
}
for(int i=1;i<n;i++){
int u,v;
read(u);
read(v);
e[u].push_back(v);
e[v].push_back(u);
}
while(l<r){
ll mid=l+(r-l+1)/2;
if(check(mid))l=mid;
else r=mid-1;
}
printf("%lld\n",l);
}
int main(){
//freopen("ansin.in","r",stdin);
//freopen("ansout.out","w",stdout);
//ios::sync_with_stdio(0);
//cin.tie(0);
//cout.tie(0);
int c,T;
read(c);
read(T);
while(T--)work();
return 0;
}