UVa 10308 Roads in the North 樹的直徑

來源:互聯網
上載者:User

題目來源:UVa 10308 Roads in the North

題意:求距離最遠的2點之間的距離

思路:裸的樹的直徑 或者樹形DP

#include <cstdio>#include <cstring>#include <queue>using namespace std;const int maxn = 100010;struct node{int to, w;node(){}node(int to, int w): to(to), w(w) {} bool operator < (const node& rhs) const{return w < rhs.w;}};vector <node> G[maxn];int dis[maxn];bool vis[maxn];int path[maxn];int p, leaf, n;void BFS(int s){memset(vis, 0, sizeof(vis));memset(dis, 0, sizeof(dis));memset(path, 0, sizeof(path));queue <int> Q;Q.push(s);vis[s] = true;while(!Q.empty()){int u = Q.front();Q.pop();for(int i = 0; i < G[u].size(); i++){node x = G[u][i];int v = x.to;if(vis[v])continue;vis[v] = true;dis[v] = dis[u] + x.w;path[v] = u;//printf("%d\n", dis[v]);if(leaf < dis[v]){p = v;leaf = dis[v];}Q.push(v);}}}int main(){char str[100];while(gets(str)){for(int i = 1; i <= 10000; i++)G[i].clear();if(strlen(str) == 0){puts("0");continue;}int u, v, w;sscanf(str, "%d %d %d", &u, &v, &w);G[u].push_back(node(v, w));G[v].push_back(node(u, w));while(gets(str) && strlen(str) > 0){sscanf(str, "%d %d %d", &u, &v, &w);G[u].push_back(node(v, w));G[v].push_back(node(u, w));}leaf = 0;BFS(1);leaf = 0;BFS(p);printf("%d\n", leaf);}return 0;}/*5 1 61 4 56 3 92 6 86 1 7*/


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.