Highway
Highway |
||
Accepted : 78 | Submit : 275 | |
Time Limit : 4000 MS | Memory Limit : 65536 KB |
HighwayIn ICPCCamp there were n towns conveniently numbered with 1,2,…,n connected with (n−1) roads. The i -th road connecting towns ai and bi has length ci . 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) cents, where δ(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. InputThe 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 ai , bi and ci .
OutputFor each test case, output an integer which denotes the result. Sample Input5 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 Sample Output19 15 |
//题意:有一棵树,问所有点到这棵树中所有点最远距离和为多少
//因为这个是树,所以,从任意一点 dfs 搜最远点,再从最远点 dfs 搜最远点,再dfs一下,这样,保存了2个最远点到任意点的距离,遍历一遍选最大的那个即可,最后减去直径,因为重复算了一次
一共就 4 n 次遍历吧,1800 ms 还行吧
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 #include <vector> 6 #include <queue> 7 using namespace std; 8 #define LL long long 9 #define INF 0x3f3f3f3f3f3f3f3f 10 #define MX 100005 11 struct To 12 { 13 int to; 14 LL c; 15 }; 16 17 int n; 18 int far; 19 LL step; 20 vector<To> road[MX]; 21 LL dis[2][MX]; 22 23 void Init() 24 { 25 for (int i=1;i<=n;i++) 26 road[i].clear(); 27 } 28 29 void dfs(int x,int pre,LL s,int kk)//所在位置,从前,距离,第几次 30 { 31 if (kk!=0) dis[kk-1][x]=s; 32 33 if (s>step) 34 { 35 far=x; 36 step=s; 37 } 38 for (int i=0;i<(int)road[x].size();i++) 39 { 40 if (road[x][i].to!=pre) 41 dfs(road[x][i].to,x,road[x][i].c+s,kk); 42 } 43 } 44 45 int main() 46 { 47 while (~scanf("%d",&n)) 48 { 49 Init(); 50 for (int i=0;i<n-1;i++) 51 { 52 int a,b,c; 53 scanf("%d%d%d",&a,&b,&c); 54 road[a].push_back((To){b,c}); 55 road[b].push_back((To){a,c}); 56 } 57 58 step=0; 59 dfs(1,0,0,0); 60 61 step=0; 62 dfs(far,0,0,1); 63 step=0; 64 dfs(far,0,0,2); 65 66 LL ans = 0; 67 for (int i=1;i<=n;i++) 68 ans += max(dis[0][i],dis[1][i]); 69 ans -= step; 70 printf("%I64d\n",ans); 71 } 72 return 0; 73 }