Bzoj 3363 poj 1985 cow marathon tree diameter

Source: Internet
Author: User

Give a tree and find the longest distance between two points.


Idea: the diameter of the bare earth tree. For the first BFs, you can search for a specific point width for the first time. Then, you can use the farthest point in the width search for the last time. The longest distance obtained is the diameter of the tree.


Code:


#include <queue>#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define MAX 80010using namespace std;int points,edges;int head[MAX],total;int next[MAX],aim[MAX],length[MAX];int f[MAX];char s[10];inline void Add(int x,int y,int len);inline void BFS(int start);int main(){cin >> points >> edges;for(int x,y,len,i = 1;i <= edges; ++i) {scanf("%d%d%d%s",&x,&y,&len,s);Add(x,y,len),Add(y,x,len);}BFS(1);int _max = 0;for(int i = 1;i <= points; ++i)if(f[i] > f[_max])_max = i;BFS(_max);int ans = 0;for(int i = 1;i <= points; ++i)if(f[i] > ans)ans = f[i];cout << ans << endl;return 0;}inline void Add(int x,int y,int len){next[++total] = head[x];aim[total] = y;length[total] = len;head[x] = total;}inline void BFS(int start){static queue<int> q;while(!q.empty())q.pop();memset(f,0x3f,sizeof(f));f[0] = f[start] = 0;q.push(start);while(!q.empty()) {int x = q.front(); q.pop();for(int i = head[x];i;i = next[i])if(f[aim[i]] > f[x] + length[i]) {f[aim[i]] = f[x] + length[i];q.push(aim[i]);}}}


Bzoj 3363 poj 1985 cow marathon tree diameter

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.