Uva10308roads in the North (DFS)

Source: Internet
Author: User

Uva10308roads in the North (DFS)

Topic links

The main topic: to give you many roads, each road is connected to two different cities, and give you the distance of the road, now requires you to find out the furthest from the distance between the two cities.

Problem-solving ideas: A start, want to use DFS, but did not think that only need to find a node Dfs once on it, but also think if every point to find once, then certainly does not work. After looking at the problem only to find once you can, because the topic is a tree, and the distance between two nodes can be through DFS, as long as the process to record the maximum value can be.

Code:

#include <cstdio>#include <cstring>#include <algorithm>#include <vector>using namespace STD;Const intMAXN =10005;intVIS[MAXN];intAnsstructNode {intID, Val; Node (intID =0,intval =0) { This->id = ID; This->val = val; }}; vector<node>V[MAXN];intDFS (intR) {intnum =0;intn = v[r].size (); VIS[R] =1; for(inti =0; I < n; i++)if(!vis[v[r][i].id]) {intTMP = DFS (v[r][i].id) + v[r][i].val;            ans = max (ans, tmp + num);        num = max (num, tmp); } Vis[r] =0;returnNum;}intMain () {Charstr[ +];intA, B, Val; while(true) {ans =0; for(inti =1; I <= MAXN-5; i++) v[i].clear (); while(Gets (str)! = NULL && str[0] !=' + ') {sscanf(STR,"%d%d%d", &a, &b, &val);            V[a].push_back (node (b, Val));        V[b].push_back (Node (A, Val)); } DFS (1);printf("%d\n", ans);if(str[0] !=' + ') Break; }return 0;}

Uva10308roads in the North (DFS)

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.