其他分享
首页 > 其他分享> > 1011 Highway 树的直径 树的最大生成树

1011 Highway 树的直径 树的最大生成树

作者:互联网

 链接:https://ac.nowcoder.com/acm/contest/26077/1011
来源:牛客网

题目描述

In ICPCCamp there were n towns conveniently numbered with 1,2,…,n1, 2, \dots, n1,2,…,n
connected with (n - 1) roads.
The i-th road connecting towns aia_iai​ and bib_ibi​ has length cic_ici​.
It is guaranteed that any two cities reach each other using only roads.

Bobo would like to build (n - 1) highways so that any two towns reach each using *only highways*.
Building a highway between towns x and y costs him δ(x,y)\delta(x, y)δ(x,y) cents,
where δ(x,y)\delta(x, y)δ(x,y) is the length of the shortest path between towns x and y using roads.

As Bobo is rich, he would like to find the most expensive way to build the (n - 1) highways.

输入描述:

The input contains zero or more test cases and is terminated by end-of-file. For each test case:

The first line contains an integer n.
The i-th of the following (n - 1) lines contains three integers aia_iai​, bib_ibi​ and cic_ici​.

* 1≤n≤1051 \leq n \leq 10^51≤n≤105
* 1≤ai,bi≤n1 \leq a_i, b_i \leq n1≤ai​,bi​≤n
* 1≤ci≤1081 \leq c_i \leq 10^81≤ci​≤108
* The number of test cases does not exceed 10.

输出描述:

For each test case, output an integer which denotes the result.
示例1

输入

复制
5
1 2 2
1 3 1
2 4 2
3 5 1
5
1 2 2
1 4 1
3 4 1
4 5 2

输出

复制
19
15

分析

要求的是根据所给的n - 1条边求最大生成树。

首先要知道,任何一个点,在这颗树上,只有连向这颗树的直径上的两个点u1,u2的路径才是最长的。

不妨假设树的直径只有两个点u1,u2。

直径之间先连接一条边,再让剩下n - 2个点按照向哪个连接路径长度长就连哪个的规律去连接。就可以生成一个n - 1条边的最大生成树了。

 

//-------------------------代码----------------------------

#define int ll
const int N = 1e5+10;
int n,m;
int dist1[N],dist2[N],c;
V<pii> e[N];

void dfs(int u,int fa,int *dist) {
    for(auto it:e[u]) {
        if(it.x == fa) continue;
        dist[it.x] = dist[u] + it.y;
        if(dist[it.x] > dist[c]) c = it.x;
        dfs(it.x,u,dist);
    }
}

void solve()
{
//    cin>>n>>m;
    ms(dist1,0);ms(dist2,0);
    fo(i,0,N-1) e[i].clear();
    fo(i,1,n-1) {
        int a,b,c;cin>>a>>b>>c;
        e[a].pb({b,c});
        e[b].pb({a,c});
    }
    dfs(1,0,dist1);
    int u1 = c;
    ms(dist1,0);
    dfs(c,0,dist1);
    int u2 = c;
    dfs(c,0,dist2);
    int d = 0;
    fo(i,1,n) {
        d += max(dist1[i],dist2[i]);
    }
    d -= dist2[c];
    cout<<d<<endl;
}
void main_init() {}
signed main(){
    AC();clapping();TLE;
    cout<<fixed<<setprecision(12);
    main_init();
    while(cin>>n)
//  while(cin>>n>>m,n,m)
//    int t;cin>>t;while(t -- )
    solve();
//    {solve(); }
    return 0;
}

/*样例区


*/

//------------------------------------------------------------

 

标签:dist,int,dfs,leq,dist1,dist2,直径,1011,Highway
来源: https://www.cnblogs.com/er007/p/16599482.html