Hlg 1750 【树的最长路径】.cpp
生活随笔
收集整理的這篇文章主要介紹了
Hlg 1750 【树的最长路径】.cpp
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
小A要從第一個城市出發走遍所有城市..
但是想要盡量走少一點路..
給出兩個城市之間連接的距離..問最少需要走多少距離..
?
思路:
如果要回到原點..最短距離相當于每一段路都走兩遍..
現在并不需要走回第一個城市..只要走遍所有城市就好..
所以找到一條從第一個城市開始的最長的路..然后用總長度*2-最長的路..
得到的就是最短的路了..
求最短路可以用dfs..bfs..
?
Tips:
深搜的時候要記得用一個vis數組..
否則會死循環..因為是一個無向圖..
?
Code:
View Code 1 #include <stdio.h> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 6 const int MAXM = 10000010; 7 const int MAXN = 100010; 8 9 struct Node 10 { 11 int to; 12 int next; 13 int w; 14 }edge[MAXM]; 15 int tot; 16 int head[MAXN]; 17 18 void add(int s, int u, int w) 19 { 20 edge[tot].to = u; 21 edge[tot].next = head[s]; 22 edge[tot].w = w; 23 head[s] = tot++; 24 25 edge[tot].to = s; 26 edge[tot].next = head[u]; 27 edge[tot].w = w; 28 head[u] = tot++; 29 } 30 31 int ans; 32 bool vis[MAXN]; 33 34 void dfs(int s, int cnt) { 35 ans = max(ans, cnt); 36 //printf("1_____s:%d cnt:%d\n", s, cnt); 37 for (int i = head[s]; i; i = edge[i].next) { 38 int to = edge[i].to; 39 if (!vis[to]) { 40 vis[to] = true; 41 dfs(edge[i].to, cnt+edge[i].w); 42 vis[to] = false; 43 } 44 45 } 46 } 47 48 int main() 49 { 50 int n, sum; 51 int a, b, c; 52 while(~scanf("%d", &n)) { 53 ans = sum = 0; 54 tot = 1; 55 memset(vis, false, sizeof(vis)); 56 memset(head, 0, sizeof(head)); 57 for (int i = 0; i < n-1; ++i) { 58 scanf("%d %d %d", &a, &b, &c); 59 add(a, b, c); 60 sum += c; 61 } 62 vis[1] = true; 63 dfs(1, 0); 64 printf("%d\n", sum*2-ans); 65 } 66 return 0; 67 }?
鏈接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1750
轉載于:https://www.cnblogs.com/Griselda/archive/2013/04/28/3048417.html
總結
以上是生活随笔為你收集整理的Hlg 1750 【树的最长路径】.cpp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SCI2012年收录的中文期刊
- 下一篇: 建设银行存款利率