POJ 1849 (diameter of tree-tree DP) (Good question)

Source: Internet
Author: User

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]&GT;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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.