SGU 149. Computer Network

來源:互聯網
上載者:User

標籤:style   blog   strong   os   for   io   

時間限制:0.25s

空間限制:4M;

題意:

       給出一顆n(n<=10000)個節點的樹,和n-1條邊的長度。求出這棵樹每個節點到最遠節點的距離;

 

 

 

 

Solution:

             對於一個節點,我們可以用DFS,在O(n)的時間內求出它的最遠節點的距離.

             顯然對於10000個節點,不可能將每一個節點都這樣求.

             那麼我們來看看,對於一個已經求過的節點我們可以做什麼:

                   假設,有節點k,他有子節點p,兩者距離為d

                   已經求得它的最遠節點距離為dis1,

                   這時對他的子節點p來說,有兩種情況:

                        一種是:p在k的與最遠節點的路徑上.

                                 這時p的最遠距離等於max(dis1-d,p的次遠距離+d);

                       另一種是:p不在k的最遠路徑上.

                                  此時p的最遠距離等於max(dis1+d,p向下的最遠距離);

              通過上面我們發現,我們需要一個節點的最遠距離和次遠距離以及p向下的最遠距離.

              幸運的是這三個量都可以通過一次對根的DFS在O(n)的時間內求出.

              最後再從根進行一次DFS遍求出每個節點的最遠距離和次遠距離就可以求出所有的答案了.

              總的時間複雜度O(n),空間複雜度O(n);

code

#include <iostream>#include <cstdio>#include <vector>#include <utility>using namespace std;#define mp make_pair#define fi first#define se second#define sz(x) ((int) (x).size())#define rd(a) scanf("%d",&a)#define rdd(a,b) scanf("%d%d",&a,&b);#define rep(i,a,b) for(int i=(a);i<=(b);i++)#define pb push_backtypedef pair<int, int> ii;typedef vector<ii> vii;const int INF = 11111;vii edge[INF];int dis[INF][2], ans[INF];int n, x, y;int dfs (int x) {dis[x][0] = 0;rep (i, 0, sz(edge[x]) - 1) {ii v = edge[x][i];int tem = dfs (v.fi)+v.se;rep (i, 0, 1)   if (tem > dis[x][i]) swap (tem, dis[x][i]);}return dis[x][0];}void DP (int x) {int tem;ans[x] = dis[x][0];rep (i, 0, sz (edge[x]) - 1) {ii v = edge[x][i];if (dis[v.fi][0] + v.se == dis[x][0])tem = dis[x][1] + v.se;elsetem = dis[x][0] + v.se;rep (i, 0, 1) if (tem > dis[v.fi][i]) swap (tem, dis[v.fi][i]);DP (v.fi);}}int main() {rd (n);rep (i, 2, n) {rdd (x, y);edge[x].pb (mp (i, y) );}dfs (1);DP (1);rep (i, 1, n) printf ("%d\n", ans[i]);}

  

              

 

聯繫我們

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