POJ - (diameter of the tree) 1849 Two

Meaning of the questions:

You give tree nodes N, the weights of each edge, and a starting position S. You have two robot, it can be run simultaneously on the tree. Each ran a side fuel costs will have to spend an edge weights (i want to repeat the calculation). Now you want to finish the whole tree, and asked how much to spend at least.

Ideas:

This question is when the thought of doing before did 19 cattle off the summer training season a question, fourth A-meeting (attendance title), two questions are to a tree, and then ask about the tree of the smallest edge weight value. We know that the diameter of the tree is without a doubt the longest, since we require a minimum cost for that is the path we want to avoid repeating long to run as far as possible. We know that to traverse a tree branch is run and will be repeated, not branches. So we selected the tree diameter as the diameter of such branches will only be run again. Repeat run of losses will be minimized.

I.e. last) ANS   = all values and edge weights multiplied by 2 (duplicate runs) - weight branches (without repeat run)

code:   (on the header section, the compiler can not post POJ) and then replace the universal head on the line, for aesthetic reasons to use universal head ....


#include<bits/stdc++.h> #define ll long long #define accept 0 using namespace std; const int maxm = 1e6+5; const int maxn = 1e5+5; const int inf = 0xffffff; struct edge{ int from; int to; int w; int next; }e[maxm]; int far; ll ans; int head[maxn]; int vis[maxn]; int dist[maxn]; int n,m,top; void add(int u,int v,int w){ e[top].from = u; e[top].to = v; e[top].w = w; e[top].next = head[u]; head[u] = top++; } void spfa(int s){ queue<int> q; for(int i = 1; i <= n ; i++) dist[i] = inf; memset(vis,false,sizeof(vis)); q.push(s); dist[s] = 0; while(!q.empty()){ int u = q.front() ; q.pop(); vis[u] = false ; for(int i = head[u] ; ~i ; i = e[i].next){ int v = e[i].to; if(dist[v] > dist[u] + e[i].w){ dist[v] = dist[u] + e[i].w; if(!vis[v]){ vis[v] = true; q.push(v); } } } } ans = 0; for(int i=1;i<=n;i++){ if(ans < dist[i]&&dist[i]!=inf){ ans = dist[i]; far = i; } } } void init(){ memset(head,-1,sizeof(head)); top =0; } ll sum; int main(){ init(); sum = 0; scanf("%d %d",&n,&m); for(int i=1;i<n;i++){ int u,v,w; scanf("%d %d %d",&u,&v,&w); sum += w; add(u,v,w); add(v,u,w); } int s = m; spfa(s); spfa(far); printf("%lld\n",sum*2-ans); return accept; }

 

Guess you like

Origin www.cnblogs.com/Tianwell/p/11404938.html