日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Hlg 1750 【树的最长路径】.cpp

發(fā)布時(shí)間:2024/10/12 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Hlg 1750 【树的最长路径】.cpp 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題意:

  小A要從第一個(gè)城市出發(fā)走遍所有城市..

  但是想要盡量走少一點(diǎn)路..

  給出兩個(gè)城市之間連接的距離..問最少需要走多少距離..

?

思路:

  如果要回到原點(diǎn)..最短距離相當(dāng)于每一段路都走兩遍..

  現(xiàn)在并不需要走回第一個(gè)城市..只要走遍所有城市就好..

  所以找到一條從第一個(gè)城市開始的最長的路..然后用總長度*2-最長的路..

  得到的就是最短的路了..

  求最短路可以用dfs..bfs..

?

Tips:

  深搜的時(shí)候要記得用一個(gè)vis數(shù)組..

  否則會(huì)死循環(huán)..因?yàn)槭且粋€(gè)無向圖..

?

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

轉(zhuǎn)載于:https://www.cnblogs.com/Griselda/archive/2013/04/28/3048417.html

總結(jié)

以上是生活随笔為你收集整理的Hlg 1750 【树的最长路径】.cpp的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。