题解:P9047 [PA 2021] Poborcy podatkowi
ds_SegmentTree · · 题解
以下内容是循序渐进的,建议自己仔细想想,实在想不出来再看对应的部分。
::::info[如果你一点思路也没有]
很明显需要树形 dp,所以我们可以设
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e6+10,B=500;
const ll inf=1e18;
vector<pair<int,int>> G[N];
int n,val[N];
ll f[N][4],h[B*2+5][2],g[B*2+5][2];
mt19937 rnd(time(0));
void dfs(int x,int fa){
vector<int> v;
for(auto [y,w]:G[x]){
if(y==fa) continue;
val[y]=w,dfs(y,x),v.push_back(y);
}
shuffle(v.begin(),v.end(),rnd);
int L=B,R=B,c=v.size()/2+1;
for(int i=0;i<B*2;++i) for(int j=0;j<2;++j) g[i][j]=-inf; g[B][0]=0;
for(auto y:v){
for(int j=L-1;j<=R+1;++j) h[j][0]=h[j][1]=-inf;
for(int j=L;j<=R;++j){
for(int k=0;k<2;++k){
if(g[j][k]>-inf){
h[j][k^1]=max(h[j][k^1],g[j][k]+f[y][2]);
h[j+1][k]=max(h[j+1][k],g[j][k]+f[y][3]);
h[j][k]=max(h[j][k],g[j][k]+f[y][0]);
h[j-1][k]=max(h[j-1][k],g[j][k]+f[y][1]);
}
}
}
L=max(L-1,max(B-c,0)),R=min(R+1,min(B+c,B*2));
for(int j=L;j<=R;++j) g[j][0]=h[j][0],g[j][1]=h[j][1];
}
if(x>1) f[x][0]=max(max(0ll,g[B][0]),g[B+1][0]+val[x]); else f[x][0]=max(0ll,g[B][0]);
f[x][1]=max(0ll,g[B][0])+val[x],f[x][2]=g[B-1][0]+val[x],f[x][3]=g[B][1]+val[x];
}
int main(){
scanf("%d",&n);
for(int i=1,a,b,c;i<n;++i){
scanf("%d%d%d",&a,&b,&c);
G[a].push_back({b,c});
G[b].push_back({a,c});
}
dfs(1,0);printf("%lld\n",f[1][0]);
return 0;
}
::::