手势密码 题解
Description
有一棵带点权的树。定义一次操作为选择树上的一条简单路径,并将这条简单路径上的所有点点权减去 \(1\) 。问至少需要多少次操作,使树上所有点的点权恰好变为 \(0\)。
\(n\le 3\times 10^6\)
Solution
不难列出线性规划式子:
\[
x_S\geq 0\\
\text{minimize}\{\sum_{S} x_S\}\\
s.t.\left\{\begin{array}{l}
\sum_{S\ni x} x_S\geq a_x\\
-\sum_{S\ni x} x_S\leq -a_x
\end{array}\right.\]
然后你用线性规划的对偶问题可以得到:
\[
s_x,t_x\geq 0\\
\text{maximize}\{\sum_{x} a_x(s_x-t_x)\}\\
s.t. \ \ \sum_{x\in S} (s_x-t_x)\leq 1
\]
然后你发现如果设 \(b_i=s_i-t_i\),那么就相当于 \(b_i\) 可以任选,然后:
\[
\text{maxisiz}\{\sum_{x} a_xb_x\}\\
s.t. \ \ \sum_{x\in S} b_x\leq 1
\]
然后你发现我们可以设 \(f_{u,d}\) 表示只考虑 \(u\) 子树时以 \(u\) 为端点的链的 \(\sum b\) 的最大值为 \(d\) 时子树内 \(\sum a_ib_i\) 的最大值。因为空链也可以,所以 \(d\in\{0,1\}\),而且可以说明的是有意义的 \(b_i\in\{-1,0,1\}\)。
Code
#include <bits/stdc++.h>
using namespace std;
#define Int register int
#define int long long
#define MAXN 3000005
template <typename T> void read (T &x){char c = getchar ();x = 0;int f = 1;while (c < '0' || c > '9') f = (c == '-' ? -1 : 1),c = getchar ();while (c >= '0' && c <= '9') x = x * 10 + c - '0',c = getchar ();x *= f;}
template <typename T,typename ... Args> void read (T &x,Args& ... args){read (x),read (args...);}
template <typename T> void write (T x){if (x < 0) x = -x,putchar ('-');if (x > 9) write (x / 10);putchar (x % 10 + '0');}
template <typename T> void chkmax (T &a,T b){a = max (a,b);}
template <typename T> void chkmin (T &a,T b){a = min (a,b);}
int a[MAXN],su[MAXN],sv[MAXN];
namespace Generate{
int n,seed;
static const int mod=1e9;
int Rand(int x){
seed=(1ll*seed*0x66CCF+19260817ll)%x+1;
seed=(1ll*seed*0x77CCF+20060428ll)%x+1;
seed=(1ll*seed*0x88CCF+12345678ll)%x+1;
seed=(1ll*seed*0x33CCCCFF+10086001ll)%x+1;
return seed;
}
void RS(int* a, int* u, int* v){ //你需要传入三个参数,分别表示点权,一条边的两个端点
int cnt=0;
for(int i=1;i<=n;i++)a[i]=Rand(mod);
for(int i=2;i<=n;i++){
int fa=Rand(i-1);
cnt++;
su[cnt]=fa,sv[cnt]=i;
}
}
};
int n,f[MAXN][2];
vector <int> g[MAXN];
void dfs (int u,int fa){
for (Int v : g[u]) if (v ^ fa) dfs (v,u);
int fuc[2];memset (fuc,0xcf,sizeof (fuc));
for (Int d = -1;d <= 1;++ d){
memset (f[u],0xcf,sizeof (f[u])),f[u][max (0ll,d)] = 0;
for (Int v : g[u]) if (v ^ fa){
int tmp[2];memset (tmp,0xcf,sizeof (tmp));
for (Int las = 0;las <= 1;++ las)
for (Int t = 0;t <= 1;++ t) if (t + d <= 1 && las + t <= 1)
chkmax (tmp[max (las,t + d)],f[u][las] + f[v][t]);
for (Int t = 0;t <= 1;++ t) f[u][t] = tmp[t];
}
for (Int t = 0;t <= 1;++ t) chkmax (fuc[t],f[u][t] + d * a[u]);
}
for (Int t = 0;t <= 1;++ t) f[u][t] = fuc[t];
}
signed main(){
int opt;read (opt);
if (opt == 1){
read (n);
for (Int i = 1;i <= n;++ i) read (a[i]);
for (Int i = 2,u,v;i <= n;++ i) read (u,v),g[u].push_back (v),g[v].push_back (u);
}
else{
read (Generate::seed,n),Generate::n = n,Generate::RS(a,su,sv);
for (Int i = 1;i <= n - 1;++ i) g[su[i]].push_back (sv[i]),g[sv[i]].push_back (su[i]);
}
dfs (1,0),write (max (f[1][0],f[1][1])),putchar ('\n');
return 0;
}