列表

详情


NC229646. Problem F. fare

描述

There are cities and they are connected by railways. In other words, the city and the railway form a tree.

There is a strange rule about the charging method in this place. The travel fare required for a passenger to travel kilometers is . Please note that passengers cannot divide a journey into several shorter journeys in order to achieve the purpose of reducing tolls.

There is an event to be held in this place. There are  contestants in the city. You have to choose a city to hold this event to minimize the sum of travel expenses for all contestants.

输入描述

Enter an integer on the first line.

The second line is integers , separated by spaces.

In the next line, each line contains three integers , indicating that there is a railway connecting cities and with a length of  kilometers.

输出描述

Output one line, including an integer, which means the minimum toll.

Ensure that the answer range does not exceed the long long type.

示例1

输入:

3
1 1 1
1 2 10
2 3 10

输出:

200

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++ 解法, 执行用时: 155ms, 内存消耗: 21524K, 提交时间: 2022-07-13 02:28:44

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N=2e5+10;
LL g[N],f[N];
struct E{
	int to,nxt;
	LL w;
}e[N<<1];
int cnt,head[N];
void add(int u,int v,int w){
	e[++cnt]={v,head[u],w};
	head[u]=cnt;
}
int c[N],n;
LL sz[N];
void dfs(int u,int fa){
	for(int i=head[u];i;i=e[i].nxt){
		int v=e[i].to;
		LL w=e[i].w;
		if(v==fa)continue;
		dfs(v,u);
		sz[u]+=sz[v];

		f[u]+=f[v]+2*g[v]*w+w*w*sz[v];
		g[u]+=g[v]+sz[v]*w;
	}
}
void dfs_(int u,int fa){
	for(int i=head[u];i;i=e[i].nxt){
		int v=e[i].to;
		LL w=e[i].w;
		if(v==fa)continue;

		f[v]=f[u]-2*w*g[v]-w*w*sz[v]+
		2*w*(g[u]-g[v]-sz[v]*w)+w*w*(sz[1]-sz[v]);

		g[v]=g[u]-sz[v]*w+(sz[1]-sz[v])*w;
		dfs_(v,u);
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%lld",&sz[i]);
	for(int i=1;i<n;i++){
		int u,v;
		LL w;
		scanf("%d %d %lld",&u,&v,&w);
		add(u,v,w);
		add(v,u,w);
	}
	dfs(1,0);
	dfs_(1,0);
	LL ans=1e18;
	for(int i=1;i<=n;i++){
		ans=min(ans,f[i]);
	}
	printf("%lld",ans);
	return 0;
}

上一题