手势密码
很巧妙的一道贪心题。
很显然我们可以想到这道题的关键在于从什么时候开始,我当前所选择的链开始拐弯。
那么我们就可以想到遍历整棵树,在回溯的过程中依次处理那些链是就地拐弯,哪些链是继续往上传,在决定一条链的开始时计算贡献决定拐弯时减去多算的贡献即可。
现在我们的瓶颈在于如何决定拐点,由于数据范围很大,期望在
首先假设我们已经得到了对于当前点
很显然,我们肯定不能能拐弯就直接拐弯。不妨分类讨论一下:
1、当
对于这种情况,我们发现我们完全不拐弯一定属于最优策略。因为在这种情况下,无论如何,
2、当
对于这种情况,我们需要尽可能多地选择拐点。因为此时取到最后
3、对于剩余的情况:
由于随着我们对于拐点的选取,
整理可得一下简单的代码:
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
namespace IO{
const int sz=1<<22;
char a[sz+5],b[sz+5],*p1=a,*p2=a,*t=b,p[105];
inline char gc(){
return p1==p2?(p2=(p1=a)+fread(a,1,sz,stdin),p1==p2?EOF:*p1++):*p1++;
}
template<class T> void gi(T& x){
x=0; char c=gc();
for(;c<'0'||c>'9';c=gc());
for(;c>='0'&&c<='9';c=gc())
x=(x<<3)+(x<<1)+(c-'0');
}
inline void flush(){fwrite(b,1,t-b,stdout),t=b; }
inline void pc(char x){*t++=x; if(t-b==sz) flush(); }
template<class T> void pi(T x,char c='\n'){
if(x<0) x=-x;
if(x==0) pc('0'); int t=0;
for(;x;x/=10) p[++t]=x%10+'0';
for(;t;--t) pc(p[t]); pc(c);
}
struct F{~F(){flush();}}f;
}
using IO::gi;
using IO::pi;
const int MAXN = 3e6 + 5;
LL ans , a[MAXN];
int n , head[MAXN] , to[MAXN << 1] , nxt[MAXN << 1] , cnt;
void add(int u , int v) {nxt[++cnt] = head[u];head[u] = cnt;to[cnt] = v;}
LL dfs(LL x , LL fa) {
LL _sum = 0 , maxn = 0;
for (int i = head[x]; i; i = nxt[i]) {
if(to[i] == fa) continue;
LL num = dfs(to[i] , x);
_sum += num , maxn = max(maxn , num);
}
LL c = min(_sum - maxn , _sum / 2);
if(a[x] <= c) {
ans -= a[x];
return 0;
}
else if(a[x] < _sum) {
LL tmp = min(_sum - a[x] , c);
ans -= tmp;
return a[x] - tmp;
}
else {
ans += a[x] - _sum;
return a[x];
}
}
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(LL* a){
for(int i = 1; i <= n; i++) a[i] = Rand(mod);
for(int i = 2; i <= n; i++){
int fa = Rand(i - 1);
add(fa , i);
add(i , fa);
}
}
};
int main() {
int ty;
gi(ty);
if(ty == 1) {
gi(n);
for (int i = 1; i <= n; ++i) gi(a[i]);
for (int i = 1; i < n; ++i) {
int u , v;
gi(u),gi(v);
add(u , v),add(v , u);
}
}
else {
gi(Generate::seed);
gi(n);
Generate::n=n;
Generate::RS(a);
}
dfs(1 , 0);
pi(ans);
return 0;
}