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)