有一棵树,树上有n个节点,每个节点点权ci,r是根节点。现在你希望依次取点,一个节点能取当且仅当它的父节点已取或它是根,第i个取的点j代价为i∗cj

贪心,交换法可以证明最大值的点必然在其父节点后马上取,因此每次拿出最大值节点和父节点合并,重复该操作直至只剩一个节点。

假设一个合并后的节点T代价为vt=ct1+2ct2+⋯+scts.
另一个节点R为vr=cr1+2cr2+⋯+lcrl,
且R是T的父节点,合并后代价为
ct1+2ct2+⋯+scts+(s+1)cr1+(s+2)cr2+⋯+(s+l)crl
=vt+vr+s∗(∑li=1ci)
对答案的贡献为s∗(∑li=1ci)
最后为的答案=(对答案的贡献+所有的c_i)

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
#include<cmath>
#include<cctype>
#include<ctime>
#include<iomanip>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<sstream>
#include<set>
using namespace std;
#define For(i,n) for(int i=1;i<=n;i++)
#define Fork(i,k,n) for(int i=k;i<=n;i++)
#define Rep(i,n) for(int i=0;i<n;i++)
#define ForD(i,n) for(int i=n;i;i--)
#define ForkD(i,k,n) for(int i=n;i>=k;i--)
#define RepD(i,n) for(int i=n;i>=0;i--)
#define Forp(x) for(int p=Pre[x];p;p=Next[p])
#define Forpiter(x) for(int &p=iter[x];p;p=Next[p])
#define Lson (o<<1)
#define Rson ((o<<1)+1)
#define MEM(a) memset(a,0,sizeof(a));
#define MEMI(a) memset(a,127,sizeof(a));
#define MEMi(a) memset(a,128,sizeof(a));
#define INF (2139062143)
#define F (1000000007)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define vi vector<int>
#define pi pair<int,int>
#define SI(a) ((a).size())
#define Pr(kcase,ans) printf("Case #%d: %I64d\n",kcase,ans);
#define PRi(a,n) For(i,n-1) cout<<a[i]<<' '; cout<<a[n]<<endl;
#define PRi2D(a,n,m) For(i,n) { \
For(j,m-1) cout<<a[i][j]<<' ';\
cout<<a[i][m]<<endl; \
}
#pragma comment(linker, "/STACK:102400000,102400000")
#define ALL(x) (x).begin(),(x).end()
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
ll mul(ll a,ll b){return (a*b)%F;}
ll add(ll a,ll b){return (a+b)%F;}
ll sub(ll a,ll b){return ((a-b)%F+F)%F;}
void upd(ll &a,ll b){a=(a%F+b%F)%F;}
int read()
{
int x=0,f=1; char ch=getchar();
while(!isdigit(ch)) {if (ch=='-') f=-1; ch=getchar();}
while(isdigit(ch)) { x=x*10+ch-'0'; ch=getchar();}
return x*f;
}
#define MAXN (1101)
int fa[MAXN];
ll t[MAXN],v[MAXN]={};
bool use[MAXN]={};
int main()
{
// freopen("F.in","r",stdin);
// freopen(".out","w",stdout);
int n,r;
while(cin>>n>>r && n) {
For(i,n) {
t[i]=1,v[i]=read();
}
For(i,n-1) {
int u=read(),v=read();
fa[v]=u;
}
For(i,n) use[i]=1;
ll ans=0;
fa[r]=0;
For(i,n) {
int p=1;
while(!use[p]) ++p;
For(j,n) if (use[j]){
if (v[j]*t[p]>v[p]*t[j]) p=j;
}
if (p==r) {
use[p]=0;
continue;
}
int f=fa[p];
while(f!=r&& !use[f]) f=fa[f];
ans+=v[p]*t[f];
v[f]+=v[p];
t[f]+=t[p];
use[p]=0;
}
cout<<ans+v[r]<<endl;
}
return 0;
}