Approximate test instructions: Send two points at a certain point to traverse all sides, spend the weight of the edge, and ask for the least cost
Idea: This is the key to the model and the longest road between the transformation of the model, can be converted, all the side traversed two times the total cost minus the longest road cost is the answer to the question, to think about, and the answer and the beginning of the dispatch is irrelevant
Find the longest road two times Dfs or BFS can, from any point BFs found one of the longest road end, and then from the end of the BFS to find a starting point
1032k79msc++1455b#include<cstdio> #include <iostream> #include <cstring> #include <algorithm > #include <queue>using namespace std;const int n=1e5+100;struct edge{int v,w; int next;} Es[n<<1];int head[n];int n,s;bool vis[n];int step[n];int sum;int bfs (int &st) {int maxn=-1; step[st]=0; memset (vis,0,sizeof (VIS)); Queue<int> que; if (!que.empty ()) Que.pop (); Que.push (ST); Vis[st]=true; while (!que.empty ()) {int Cur=que.front (); Que.pop (); for (int i=head[cur];~i;i=es[i].next) {int v=es[i].v; if (!vis[v]) {Que.push (v); STEP[V]=STEP[CUR]+ES[I].W; if (STEP[V]>MAXN) {maxn=step[v]; St=v; } vis[v]=true; }}} return MAXN;} void Ini () {memset (head,-1,sizeof (head)); sum=0;} int main () {while (~scanf ("%d%d", &n,&s)) {ini (); for (int i=1;i<n;i++) {int u,v,w; scanf ("%d%d%d", &u,&v,&w); Sum+=w; Es[i].v=v,es[i].w=w,es[i].next=head[u]; Head[u]=i; ES[I+N].V=U,ES[I+N].W=W,ES[I+N].NEXT=HEAD[V]; Head[v]=i+n; } BFS (s); printf ("%d\n", 2*sum-bfs (s)); } return 0;}
POJ 1849 (diameter of tree-tree DP) (Good question)