The wheel of the history rolling forward, our king conquered a new region in a distant continent.
There are N towns (numbered from 1 to N) in this region connected by several roads. It's confirmed that there is exact one route between any two towns. Traffic is important while controlled colonies are far away from the local country. We define the capacity C(i, j) of a road indicating it is allowed to transport at most C(i, j) goods between town i and town j if there is a road between them. And for a route between i and j, we define a value S(i, j) indicating the maximum traffic capacity between i and j which is equal to the minimum capacity of the roads on the route.
Our king wants to select a center town to restore his war-resources in which the total traffic capacities from the center to the other N - 1 towns is maximized. Now, you, the best programmer in the kingdom, should help our king to select this center.
Input
There are multiple test cases.
The first line of each case contains an integer N. (1 ≤ N ≤ 200,000)
The next N - 1 lines each contains three integers a, b, c indicating there is a road between town a and town b whose capacity is c. (1 ≤ a, b ≤ N, 1 ≤ c ≤ 100,000)
Output
For each test case, output an integer indicating the total traffic capacity of the chosen center town.
Sample Input
4 1 2 2 2 4 1 2 3 1 4 1 2 1 2 4 1 2 3 1
Sample Output
4 3
题目要求一棵树中到其他点路径权值和最大的点
本题容易想到图论中最大生成树,但二者有着明显的差别,最大生成树每条边只记一次,但本题有的边要记多次所以才会出现题目所说的最大权值的点
又容易想到树形DP,但树形DP一来时间复杂度很高,不适用本题,二来状态转移方程在本题中不太好找,所以应该想想贪心,找一个正确的贪心策略;
对于本题可以将便首先从大到小排序,反正就是n-1条嘛!我从大到小的选,但要合并的时候保证选权值大的一个方向。
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; const int MAX=200000+100; struct Edg { int u,v,p; }E[MAX]; int par[MAX]; int num[MAX]; long long cost[MAX]; bool cmp(Edg a,Edg b) { return a.p>b.p; } long long Max(long long a,long long b ) { return a<b?b:a; } int Get_par(int a) //查找a的父亲节点并压缩路径 { if(par[a]==a) return par[a]; //注意语句的顺序 par[a]=Get_par(par[a]); return par[a]; } void Merge(int a,int b) //合并a,b { num[b]+=num[a]; par[a]=b; } int main() { int n,i; while(~scanf("%d",&n)) { for(i=0;i<n-1;i++) scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].p); sort(E,E+n-1,cmp); for(i=1;i<=n;i++) par[i]=i,num[i]=1,cost[i]=0; for(i=0;i<n-1;i++) { int pu=Get_par(E[i].u); int pv=Get_par(E[i].v); long long tmpu=(long long)(E[i].p)*num[pv]+cost[pu]; long long tmpv=(long long)(E[i].p)*num[pu]+cost[pv]; if(tmpu>tmpv) { cost[pu]=tmpu; Merge(pv,pu); } else { cost[pv]=tmpv; Merge(pu,pv); } // if(pu!=pv) // { /* cost[pu]=Max((long long)(E[i].p)*num[pv]+cost[pu],(long long)(E[i].p)*num[pu]+cost[pv]); num[pu]+=num[pv]; par[pv]=pu;///此处一改可能导致有的节点的父亲节点并不是指向根节点的*/ // } } printf("%lld\n",cost[Get_par(1)]);//cost[Get_par(1)]); } return 0; }