NC218915. FullDepthMorningShow
描述
输入描述
The first line of input is a single integer n (). The next line has n space-separated integers (), the tax in each city. The following n - 1 lines each have 3 integers, , meaning the i-th road connects cities and (), with a toll of ().
输出描述
Output n lines. On the i-th line, output a single integer: the cost of purchasing tickets if city i wins the contest.
示例1
输入:
5 2 5 3 4 1 1 2 2 2 4 5 4 3 3 5 2 6
输出:
130 159 191 163 171
示例2
输入:
6 4 3 3 4 3 3 1 3 2 2 1 1 1 4 6 4 5 6 6 4 2
输出:
209 206 232 209 336 232
C++(clang++11) 解法, 执行用时: 387ms, 内存消耗: 38940K, 提交时间: 2021-03-08 14:04:09
#include<bits/stdc++.h> using namespace std; typedef long long ll; unordered_map<int,unordered_map<int,int> >mp; vector<int> v[100500]; int i,n,m,x,y,z; ll res[100500],a[100500],b[100500],c[100500],s,a0[100500]; void dfs1(int x,int fa){ for(int i:v[x]){ if(i!=fa){ dfs1(i,x); if(x!=1){a[x]+=a[i];} b[x]+=b[i]; res[1]+=a[i]*mp[i][x]; c[1]+=b[i]*mp[i][x]; } } } void dfs2(int x,int fa){ if(x!=1){ res[x]=res[fa]+(s-2*a[x])*mp[fa][x]; c[x]=c[fa]+(n-2*b[x])*mp[fa][x]; } for(int i:v[x]){ if(i!=fa){dfs2(i,x);} } } int main(){ scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%lld",&a0[i]); a[i]=a0[i]; s+=a[i]; b[i]=1; } for(i=1;i<n;i++){ scanf("%d%d%d",&x,&y,&z); mp[x][y]=mp[y][x]=z; v[y].push_back(x); v[x].push_back(y); } dfs1(1,0);dfs2(1,0); for(i=1;i<=n;i++){printf("%lld\n",res[i]+c[i]*a0[i]);} }