列表

详情


NC218915. FullDepthMorningShow

描述



All boring tree-shaped lands are alike, while all exciting tree-shaped lands are exciting in their own special ways. What makes Treeland more exciting than the other tree-shaped lands are the raddest radio hosts in the local area: Root and Leaf. Every morning on FM 32.33 (repeating of course), Root and Leaf of The Full Depth Morning Show serve up the hottest celebrity gossip and traffic updates.

The region of Treeland is made of n cities, connected by n - 1 roads such that between every pair of cities there is exactly one simple path. The i-th road connects cities u_i and v_i, and has a toll of w_i.

To reward their loyal listeners, The Full Depth Morning Show is giving away a number of travel packages! Root and Leaf will choose n - 1 lucky residents from the city that sends them the most fan mail. Each of those residents then gets a distinct ticket to a different city in Treeland.

Each city in Treeland has its own tax on prizes: t_i. Let be the sum of the tolls on each road on the only simple path from city u to v. For a trip from city u to city v, the cost of that trip is then .


The map of Treeland corresponding to the first sample input.

The shock jocks haven't quite thought through how much their prize is worth. They need to prepare a report to the radio executives, to summarize the expected costs. For each city that could win the prize, what is the total cost of purchasing all the tickets?

输入描述

The first line of input is a single integer n (). The next line has n space-separated integers t_i (), the tax in each city. The following n - 1 lines each have 3 integers, u_i, v_i, w_i, meaning the i-th road connects cities u_i and v_i (), with a toll of w_i ().

输出描述

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]);}
}

上一题