【牛客 - 188C】水图(bfs树的直径,思维)
生活随笔
收集整理的這篇文章主要介紹了
【牛客 - 188C】水图(bfs树的直径,思维)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題干:
鏈接:https://ac.nowcoder.com/acm/contest/188/C
來(lái)源:牛客網(wǎng)
?
小w不會(huì)離散數(shù)學(xué),所以她van的圖論游戲是送分的
小w有一張n個(gè)點(diǎn)n-1條邊的無(wú)向聯(lián)通圖,每個(gè)點(diǎn)編號(hào)為1~n,每條邊都有一個(gè)長(zhǎng)度
小w現(xiàn)在在點(diǎn)x上
她想知道從點(diǎn)x出發(fā)經(jīng)過(guò)每個(gè)點(diǎn)至少一次,最少需要走多少路
輸入描述:
第一行兩個(gè)整數(shù) n,x,代表點(diǎn)數(shù),和小w所處的位置 第二到第n行,每行三個(gè)整數(shù) u,v,w,表示u和v之間有一條長(zhǎng)為w的道路輸出描述:
一個(gè)數(shù)表示答案示例1
輸入
復(fù)制
3 1 1 2 1 2 3 1輸出
復(fù)制
2備注:
1 ≤ n ≤ 50000 , 1 ≤ w ≤ 2147483647解題報(bào)告:
? 和? ?牛客369的C一樣的思維。
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 ;//返回的點(diǎn)坐標(biāo) 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() {int x;cin>>n>>x;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(x,ans1);//printf("ans2 = %d\n",ans2);printf("%lld\n",1LL*ans1 + (sum-ans1)*2);return 0 ; }?
總結(jié)
以上是生活随笔為你收集整理的【牛客 - 188C】水图(bfs树的直径,思维)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【CodeForces - 483C】D
- 下一篇: 【HDU - 2570】迷瘴 (贪心,水