Poj1985-cow marathon

Source: Internet
Author: User


Want to see more problem-solving reports:Http://blog.csdn.net/wangjian8006/article/details/7870410

Reprinted please indicate the source:Http://blog.csdn.net/wangjian8006

There are n farms, and the N farms have some edge connections. Then you need to find two points to maximize the path length and output the maximum length.

Solution: because there is only one path, this figure is a tree. If we know a tree, we can find the maximum distance between two points. BFS can solve this problem twice.
First BFS: Search from any point and find the longest point from this point.
The second BFS: search from the point found by the first BFs, and find out the longest point in the BFS is the answer.
This is the same idea as poj1383.

 

/* Memory 1784 ktime 204 Ms */# include <queue> # include <iostream> using namespace STD; # define maxv 50000 # define MaxE 100000 typedef struct {int T, W, next;} edge; edge [MaxE]; int n, m; int e, head [maxv], record [maxv]; void addedge (int s, int t, int W) {edge [e]. T = T; edge [e]. W = W; edge [e]. next = head [s]; head [s] = e ++;} int BFS (int s, int flag) {int I, V, T; int TMP = 0, tmpi = s; queue <int> q; memset (record,-1, sizeof (record); record [s ] = 0; q. Push (s); While (! Q. Empty () {v = Q. Front (); q. Pop (); for (I = head [v]; I! =-1; I = edge [I]. next) {T = edge [I]. t; If (record [T] =-1) {record [T] = record [v] + edge [I]. w; If (record [T]> TMP) {TMP = record [T]; tmpi = T;} Q. push (t) ;}} return flag? Tmpi: TMP;} int main () {int A, B, W, ans; char C; while (~ Scanf ("% d \ n", & N, & M) {memset (Head,-1, sizeof (head); E = 0; while (M --) {scanf ("% d % C \ n", & A, & B, & W, & C); addedge (A, B, w); addedge (B, A, W);} A = BFS (1,1); ans = BFS (A, 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.