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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【牛客 - 369C】小A与欧拉路(bfs树的直径)

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【牛客 - 369C】小A与欧拉路(bfs树的直径) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題干:

鏈接:https://ac.nowcoder.com/acm/contest/369/C
來源:牛客網
?

小A給你了一棵樹,對于這棵樹上的每一條邊,你都可以將它復制任意(可以為0)次(即在這條邊連接的兩個點之間再加一條邊權相同的邊),求所有可能新形成的圖中歐拉路的最短長度

歐拉路:從圖中任意一個點開始到圖中任意一個點結束的路徑,并且圖中每條邊只通過恰好一次

輸入描述:

第一行一個數 n ,表示節點個數

接下來 n-1 行,每行三個整數 u,v,w,表示有一條 u 到 v 邊權為 w 的無向邊

保證數據是一棵樹

輸出描述:

一行一個整數,表示答案

示例1

輸入

復制

4 1 2 1 1 3 1 1 4 2

輸出

復制

5

說明

一種可能的方案為復制 <1,2,1> 這條邊一次,歐拉路為4->1->2->1->3

備注:

1≤n≤2×1051≤n≤2×105
1≤ui,vi≤n1≤ui,vi≤n
1≤wi≤1041≤wi≤104

解題報告:

? ?思維題,不難發現選擇樹的直徑,剩下的掛到鏈上,這樣一定是最優解。

AC代碼:

#include <queue> #include <cstdio> #include <cstring> #include <iostream> #define ll long long using namespace std; const int MAX = 6e5 + 5 ; const int INF = 0x3f3f3f3f; struct Node {int to;int w;int ne; } e[MAX]; struct point {int pos,c;point(){}point(int pos,int c):pos(pos),c(c){}}; int n; int head[MAX]; int cnt = 0 ; bool vis[MAX]; void init() {cnt = 0;memset(head,-1,sizeof(head)); } void add(int u,int v,int w) {e[cnt].to = v;e[cnt].w = w;e[cnt].ne = head[u];head[u] = cnt;cnt++; } int bfs(int x,int &w) {queue <point> q;int maxx = 0;int retp = x ;//返回的點坐標 memset(vis,0,sizeof(vis) );q.push(point(x,0));vis[x] = 1;point now;while(q.size() ) {point cur = q.front();q.pop();for(int i = head[cur.pos]; i!=-1; i=e[i].ne) {if(vis[e[i].to]) continue;vis[e[i].to] = 1;now.pos = e[i].to;now.c = cur.c + e[i].w;if(now.c>maxx) {maxx = now.c;retp = now.pos;}q.push(now);}//w = maxx;}w = maxx;return retp; } int main() {cin>>n;init();int u,v,w;ll sum = 0;for(int i = 1; i<=n-1; i++) {scanf("%d%d%d",&u,&v,&w);add(u,v,w);add(v,u,w);sum += w;}int ans1 = 0,ans2 = 0;u = bfs(1,ans1);v = bfs(u,ans2);//printf("ans2 = %d\n",ans2);printf("%lld\n",1LL*ans2 + (sum-ans2)*2);return 0 ; } /* 9 1 8 1 1 2 2 2 7 3 2 3 1 3 5 3 3 4 10 4 9 4 5 6 2*/

?

總結

以上是生活随笔為你收集整理的【牛客 - 369C】小A与欧拉路(bfs树的直径)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。