2025 ICPC Asia EC 网络预选赛第一场 D题思路分享(dp)
https://qoj.ac/contest/2513/problem/14304/statement/zh_cn
题意
给定一棵树,每个点有点权,任意断边将树分成若干连通分量,让所有连通分量的最大值 \(-\) 最小值之和最大,求这个最大值.
\(1\le n \le 10^6\).
思路
考虑 \(dp\),需要维护未封闭连通块的最大值和最小值.
可以提前决策,钦定 \(a_i\) 为最值,这样需要维护最大值和最小值有没有被决策,转移讨论是否封闭连通块即可.
时间复杂度 \(\mathcal{O}(16n)\).
代码
//author:kzssCCC
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 9e18;
void solve(){
int n;
cin >> n;
vector<ll> a(n+1);
for (int i=1;i<=n;i++){
cin >> a[i];
}
vector<vector<int>> adj(n+1);
for (int i=0;i<n-1;i++){
int u,v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<vector<ll>> dp(n+1,vector<ll>(4,-INF));
for (int i=1;i<=n;i++){
dp[i][0] = 0;
}
function<void(int,int)> dfs = [&](int u,int par){
for (auto& v:adj[u]){
if (v==par) continue;
dfs(v,u);
vector<ll> ndp(4,-INF);
for (int q=0;q<4;q++){
if (dp[v][q]==-INF) continue;
for (int p=0;p<4;p++){
if (dp[u][p]==-INF) continue;
if ((p&q)==0){
ndp[p|q] = max(ndp[p|q],dp[u][p]+dp[v][q]);
}
if (q==3){
ndp[p] = max(ndp[p],dp[u][p]+dp[v][q]);
}
}
}
dp[u] = ndp;
}
auto ndp = dp[u];
for (int p=0;p<4;p++){
if (dp[u][p]==-INF) continue;
if ((p&1)==0){
ndp[p|1] = max(ndp[p|1],dp[u][p]+a[u]);
}
if ((p>>1&1)==0){
ndp[p|2] = max(ndp[p|2],dp[u][p]-a[u]);
}
}
dp[u] = ndp;
};
dfs(1,-1);
cout << dp[1][3] << '\n';
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--) solve();
return 0;
}

浙公网安备 33010602011771号