Highway |
||
Accepted : 122 | Submit : 393 | |
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 SourceXTU OnlineJudge |
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 const int inf=(1<<30); 5 const int maxn=100005; 6 ll pos; 7 ll n,ans,vis[maxn],in[maxn]; 8 vector<pair<int,int>>e[maxn]; 9 ll sum; 10 void dfs(int v,ll cnt) 11 { 12 if(ans<cnt) 13 { 14 ans=cnt; 15 pos=v; 16 } 17 if(vis[v])return; 18 vis[v]=1; 19 for(int i=0; i<e[v].size(); i++) 20 // cout<<e[v][i].first; 21 if(!vis[e[v][i].first]) 22 dfs(e[v][i].first,cnt+e[v][i].second); 23 } 24 ll dis1[123456],dis2[123456]; 25 void DFS(int v,ll cnt,ll dis[]) 26 { 27 if(vis[v]) return; 28 vis[v]=1; 29 dis[v]=cnt; 30 for(int i=0; i<e[v].size(); i++) 31 // cout<<e[v][i].first; 32 if(!vis[e[v][i].first]) 33 DFS(e[v][i].first,cnt+e[v][i].second,dis); 34 } 35 int main() 36 { 37 int n,m; 38 ans=0; 39 while(~scanf("%d",&n)) 40 { 41 ans=0; 42 memset(dis1,0,sizeof(dis1)); 43 memset(dis2,0,sizeof(dis2)); 44 memset(in,0,sizeof(in)); 45 memset(vis,0,sizeof(vis)); 46 for(int i=0;i<=n;i++) 47 { 48 e[i].clear(); 49 } 50 for(int i=1; i<n; i++) 51 { 52 ll u,v,w; 53 scanf("%d%d%d",&u,&v,&w); 54 e[u].push_back({v,w}); 55 e[v].push_back({u,w}); 56 } 57 dfs(1,0); 58 ll cnt=ans; 59 ans=0; 60 memset(vis,0,sizeof(vis)); 61 ans=0; 62 DFS(pos,0,dis1); 63 memset(vis,0,sizeof(vis)); 64 ans=0; 65 dfs(pos,0); 66 67 memset(vis,0,sizeof(vis)); 68 DFS(pos,0,dis2); 69 memset(vis,0,sizeof(vis)); 70 ll cot=ans; 71 //cout<<cot<<" "<<cnt<<endl; 72 ll Max=max(cnt,cot); 73 //cout<<Max<<endl; 74 sum=0; 75 for(int i=1;i<=n;i++) 76 { 77 sum+=max((ll)dis1[i],(ll)dis2[i]); 78 } 79 printf("%lld ",sum-Max); 80 } 81 return 0; 82 }