真心不知道这道题写线段树的人怎么想的,网上居然没有长链剖分的题解,哎,这道题就是一道标准的长链剖分,不带合并,deep存边权,sort取前k大就行了,SCOI2016 day1 t1的原版,我无力吐槽。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
template<class T>inline void read(T &res){
static char ch;register int flag=1;
while((ch=getchar())<'0'||ch>'9')if(ch=='-')flag=-1;res=ch-48;
while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-48;res*=flag;
}
const int N = 200005;
int n,k,tot,fa[N],head[N],son[N];
long long ans,sz[N],g[N],num[N],dep[N];
struct data{
int to,nxt;
}E[N<<1];
inline void addedge(int x,int y){
E[++tot].nxt=head[x],head[x]=tot,E[tot].to=y;
}
void dfsf(int x,int f){
fa[x]=f;sz[x]=dep[x];
for(register int v,i=head[x];i;i=E[i].nxt){
if(v=E[i].to,v!=f){
dep[v]=dep[x]+num[v],dfsf(v,x);
if(sz[v]>sz[son[x]])son[x]=v,sz[x]=sz[v];
}
}
}
void dfss(int x,long long sum){
if(son[x])dfss(son[x],sum+num[son[x]]);
else g[x]=sum;
for(register int v,i=head[x];i;i=E[i].nxt){
if(v=E[i].to,v!=fa[x]&&v!=son[x])dfss(v,num[v]);
}
}
int cmp(long long a,long long b){
return a>b;
}
int main(){
read(n),read(k);
for(register int i=1;i<=n;i++)read(num[i]);
for(register int x,y,i=1;i<n;i++)
read(x),read(y),addedge(x,y),addedge(y,x);
dfsf(1,0),dfss(1,num[1]);
sort(g+1,g+1+n,cmp);
for(register int i=1;i<=k;i++)ans+=g[i];
printf("%lld",ans);
return 0;
}