思路:
设$sum[i]表示i的子树中a[i]的和$
$b[1]=\Sigma a[i]*dis[i] = \Sigma _{i=2} ^n sum[i]$
$b[x]-b[fa[x]]=sum[1]-2*sum[x]$
$sum[1]={\Sigma_{i=2}^n (b[x]-b[fa[x]])+2*b[1] \over n-1}$
$求出sum[1]以后根据a[x]=sum[x]-\Sigma_{v是x的儿子} sum[v]带入求出其它值即可$
$复杂度O(n)$
//By SiriusRen#include#include using namespace std;#define int long longconst int N=600500;int n,xx,yy,first[N],next[N],v[N],tot,fa[N],rev[N],cnt,b[N],X;long long sum[N],ans[N];void add(int x,int y){v[tot]=y,next[tot]=first[x],first[x]=tot++;}void dfs(int x){ rev[++cnt]=x; for(int i=first[x];~i;i=next[i])if(v[i]!=fa[x]) fa[v[i]]=x,dfs(v[i]);}void dfs2(int x){ ans[x]=sum[x]; for(int i=first[x];~i;i=next[i])if(v[i]!=fa[x]) dfs2(v[i]),ans[x]-=sum[v[i]];}signed main(){ memset(first,-1,sizeof(first)); scanf("%lld",&n); for(int i=1;i