HDU 2196 Computer(求樹上每個節點到其它點的最遠距離)

來源:互聯網
上載者:User

標籤:

解題思路:

求出樹的直徑的兩個端點,則樹上每個節點到其他點的最遠距離一定是到這兩個端點的距離中最長的那一個。

#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>#include <vector>#include <queue>#define LL long longusing namespace std;const int MAXN = 100000 + 10;struct Edge{    int to, next, w;}edge[2 * MAXN];int tot;int head[MAXN];int dis[MAXN];int N, M;int D[MAXN];void init(){    tot = 0;    memset(head, -1, sizeof(head));    memset(D, 0, sizeof(D));}void addedge(int u, int v, int w){    edge[tot].to = v;    edge[tot].next = head[u];    edge[tot].w = w;    head[u] = tot++;}int dfs(int u, int pre = -1){    int ans = u;    for(int i=head[u];i!=-1;i=edge[i].next)    {        int v = edge[i].to;        if(v == pre) continue;        dis[v] = dis[u] + edge[i].w;        int dv = dfs(v, u);        if(dis[ans] < dis[dv]) ans = dv;    }    return ans;}int solve(int u){    dis[u] = 0;    u = dfs(u);    dis[u] = 0;    int v = dfs(u);    for(int i=1;i<=N;i++) D[i] = max(D[i], dis[i]);    dis[v] = 0;    dfs(v);    for(int i=1;i<=N;i++) D[i] = max(D[i], dis[i]);    for(int i=1;i<=N;i++) cout << D[i] << endl;}int main(){    while(scanf("%d", &N)!=EOF)    {        int v, w;        init();        for(int i=2;i<=N;i++)        {            scanf("%d%d", &v, &w);            addedge(i, v, w);            addedge(v, i, w);        }        solve(1);    }    return 0;}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

HDU 2196 Computer(求樹上每個節點到其它點的最遠距離)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.