Poj1985 cow marathon --- tree diameter

Source: Internet
Author: User

The diameter of the tree is the length of the longest path in the tree.

Two DFS requests are used to obtain the farthest point P from any point for the first time,

The second time we get the farthest point from P, this path is the longest path, that is, the longest path.


#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <cmath>#include <algorithm>#include <vector>#include <queue>#include <map>#define inf 0x3f3f3f3f#define eps 1e-6#define ll __int64using namespace std;struct node{    int v,w,next;}e[80010];int n,m,ans,p,h,head[40010],vis[40010];void addedge(int a,int b ,int c){    e[h].v=b;    e[h].w=c;    e[h].next=head[a];    head[a]=h++;}void init(){    memset(head,-1,sizeof head);    h=0;}void dfs(int x,int num){    vis[x]=1;    if(num>ans) ans=num,p=x;    for(int i=head[x];i!=-1;i=e[i].next)    {        if(!vis[e[i].v])            dfs(e[i].v,num+e[i].w);    }}int main(){    int a,b,c;    char s[10];    while(~scanf("%d%d",&n,&m))    {        init();        while(m--)        {            scanf("%d%d%d%s",&a,&b,&c,s);            addedge(a,b,c);            addedge(b,a,c);        }        ans=0;        memset(vis,0,sizeof vis);        dfs(1,0);        memset(vis,0,sizeof vis);        dfs(p,0);        printf("%d\n",ans);    }    return 0;}


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.