zoukankan      html  css  js  c++  java
  • POJ2631 树最长路径dfsDP重写

    前文:http://www.cnblogs.com/htfy/archive/2013/03/06/2946741.html。

    优化内存

    Problem: 2631 User: HTwood
    Memory: 1160K Time: 32MS
    Language: Pascal Result: Accepted
    program p2631;
    
    TYpe
     rec=record
      e,w,next:longint;
     end;
     
    Var
     a:array[0..30000] of rec;
     b,f1,f2,f3,d1,d2:array[0..30000] of longint;
     v,exist:array[0..30000] of boolean;
     n,ss,ee,ww,i,ans,top,h:longint;
    
    Procedure fopen;
      begin
      assign(input,'p2631.in');
      assign(output,'p2631.out');
      reset(input);
      rewrite(output);
    end;
    
    Procedure fclose;
      begin
      close(input);
      close(output);
    end;
    
    Function max(a,b:longint):longint;inline;
      begin
      if a>b then exit(a) else exit(b);
    end;
    
    Procedure Add(ss,ee,ww:longint);
      begin
      inc(top);
      with a[top] do
        begin
        e:=ee;
        w:=ww;
        next:=b[ss];
      end;
      b[ss]:=top;
    end;
    
    Procedure dfs1(P,fa:longint);
    var
     x:rec;
     g:longint;
      begin
      g:=b[p];
      //writeln('(',p,',',fa,')');
      while g>0 do
        begin
        x:=a[g];
        g:=x.next;
        if x.e<>fa then dfs1(x.e,p);
        if (f1[x.e]+x.w>f1[p]) and (x.e<>fa) then
          begin
          d1[p]:=x.e;
          f1[p]:=f1[x.e]+x.w;
        end;
      end;
      
      g:=b[p];
      while g>0 do
        begin
        x:=a[g];
        g:=x.next;
        if (f1[x.e]+x.w>f2[p]) and (x.e<>d1[p]) and (x.e<>fa) then
          begin
          d2[p]:=x.e;
          f2[p]:=f1[x.e]+x.w;
        end;
      end;
    end;
    
    Procedure dfs2(P,fa,wf:longint);
    var
     g:longint;
     x:rec;
      begin
      if p<>h then
        if d1[fa]<>p then f3[p]:=max(f1[fa],f3[fa])+wf else f3[p]:=max(f2[fa],f3[fa])+wf;
      g:=b[p];
      while g>0 do
        begin
        x:=a[g];
        g:=x.next;
        if x.e<>fa then dfs2(x.e,p,x.w);
      end;
    end;
    
    
      begin
    
      n:=0;top:=0;fillchar(exist,sizeof(exist),false);
      while not eof do
        begin
        readln(ss,ee,ww);
        exist[ss]:=true;
        exist[ee]:=true;
        n:=max(n,ss);
        n:=max(n,ee);
        Add(ss,ee,ww);
        Add(ee,ss,ww);
      end;
      fillchar(v,sizeof(v),false);
      h:=1;
      dfs1(h,0);
      dfs2(h,0,0);
      for i:=1 to n do
        ans:=max(ans,max(f1[i],max(f2[i],f3[i])));
      writeln(ans);
    
    end.
    
  • 相关阅读:
    Oracle Function REGEXP
    Asp.net 注册IIS
    SAP모듈
    C# 程序中,不使用TNS File 中的服务名进行数据库连接
    跟我一起学XNA(2)让物体动起来②(附源码)
    ubuntu显卡的几个帖子
    每秒改变一次背景颜色以及由此引发的一些有趣的小事情(.net方向)
    to myself
    vi编辑器上下左右键盘变成ABCD
    一个最简单的linux hello world模块
  • 原文地址:https://www.cnblogs.com/htfy/p/2971805.html
Copyright © 2011-2022 走看看