【HDOJ2196】Computer(樹的直徑,樹形DP)

來源:互聯網
上載者:User

標籤:ssi   bsp   else   hdoj   處理   sig   proc   pre   not   

題意:給定一棵N個點樹,詢問這個樹裡面每個點到樹上其他點的最大距離。

n<=10000

思路:設f[u,1],f[u,2]為以U為根向下的最長與次長,g[u,1],g[u,2]為從哪個兒子轉移來

         第一次dfs用V更新U,第二次dfs用U更新V,因為有V向U往上走的情況,這樣做就可以處理了

         可以發現這些數值中取最大值就是樹的直徑了

 1 var f,g:array[1..21000,1..2]of longint; 2     head,vet,next,len:array[1..21000]of longint; 3     n,x,y,i,tot:longint; 4  5 procedure add(a,b,c:longint); 6 begin 7  inc(tot); 8  next[tot]:=head[a]; 9  vet[tot]:=b;10  len[tot]:=c;11  head[a]:=tot;12 end;13 14 procedure dfs(u,fa:longint);15 var e,v,t:longint;16 begin17  e:=head[u];18  while e<>0 do19  begin20   v:=vet[e];21   if v<>fa then22   begin23    dfs(v,u);24    t:=f[v,1]+len[e];25    if t>f[u,1] then26    begin27     f[u,2]:=f[u,1]; g[u,2]:=g[u,1];28     f[u,1]:=t; g[u,1]:=v;29    end30     else if t>f[u,2] then31     begin32      f[u,2]:=t; g[u,2]:=v;33     end;34   end;35   e:=next[e];36  end;37 end;38 39 procedure dfs2(u,fa:longint);40 var e,v,t:longint;41 begin42  e:=head[u];43  while e<>0 do44  begin45   v:=vet[e];46   if v<>fa then47   begin48    t:=f[u,1]+len[e];49    if v=g[u,1] then t:=f[u,2]+len[e];50    if t>f[v,1] then51    begin52     f[v,2]:=f[v,1]; g[v,2]:=g[v,1];53     f[v,1]:=t; g[v,1]:=u;54    end55     else if t>f[v,2] then56     begin57      f[v,2]:=t; g[v,2]:=u;58     end;59    dfs2(v,u);60   end;61   e:=next[e];62  end;63 end;64 65 begin66  assign(input,‘2196.in‘); reset(input);67  assign(output,‘2196.out‘); rewrite(output);68  while not eof do69  begin70   fillchar(head,sizeof(head),0);71   tot:=0;72   fillchar(f,sizeof(f),0);73   fillchar(g,sizeof(g),0);74   read(n);75   if n=0 then break;76   for i:=2 to n do77   begin78    read(x,y);79    add(i,x,y);80    add(x,i,y);81   end;82   dfs(1,-1);83   dfs2(1,-1);84   for i:=1 to n do writeln(f[i,1]);85  end;86  close(input);87  close(output);88 end.

 

【HDOJ2196】Computer(樹的直徑,樹形DP)

聯繫我們

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