zoukankan      html  css  js  c++  java
  • bzoj 2435 BFS

    我们可以先将无根树变成有根树,随便选一个点当根就行了,我们选1,bfs求出来每个点 

    的size值,代表以它为根节点的子树中有多少个节点,(dfs可能会爆栈),然后再对于每一条

    边算就好了

    我tle了,也不知道咋会事儿,可能是pascal的int64的运算有些耗时。。。。

    /**************************************************************
        Problem: 2435
        User: BLADEVIL
        Language: Pascal
        Result: Time_Limit_Exceed
    ****************************************************************/
     
    //By BLADEVIL
    var
        n                       :longint;
        pre, other, last, len   :array[0..2000010] of int64;
        l                       :longint;
        flag                    :array[0..1000010] of boolean;
        size, que, dep          :array[0..1000010] of int64;
        ans                     :int64;
        fuse                    :array[0..2000010] of boolean;
         
    procedure connect(x,y,z:longint);
    begin
        inc(l);
        pre[l]:=last[x];
        last[x]:=l;
        other[l]:=y;
        len[l]:=z;
    end;
         
    procedure init;
    var
        i                       :longint;
        x, y, z                 :longint;
         
    begin
        read(n);
        for i:=1 to n-1 do
        begin
            read(x,y,z);
            connect(x,y,z);
            connect(y,x,z);
        end;
    end;
     
    procedure bfs;
    var
        h, t, cur               :longint;
        q, p                    :longint;
    begin
        h:=0; t:=1;
        que[1]:=1;
        flag[1]:=true;
        while h<>t do
        begin
            inc(h);
            cur:=que[h];
            q:=last[cur];
            while q<>0 do
            begin
                p:=other[q];
                if not flag[p] then
                begin
                    fuse[q]:=true;
                    inc(t);
                    que[t]:=p;
                    dep[p]:=dep[cur]+1;
                    flag[p]:=true;
                end;
                q:=pre[q];
            end;
        end;
    end;
     
    procedure main;
    var
        i                       :longint;
        q, p                    :longint;
    begin
        bfs;
        for i:=n downto 1 do
        begin
            q:=last[que[i]];
            size[que[i]]:=1;
            while q<>0 do
            begin
                p:=other[q];
                if dep[p]>dep[que[i]] then inc(size[que[i]],size[p]);
                q:=pre[q];
            end;
        end;
        for i:=1 to l do if fuse[i] then ans:=ans+abs(n-2*size[other[i]])*len[i];
        writeln(ans);
    end;
     
    begin
        init;
        main;
    end.
  • 相关阅读:
    基于 IAR 修改工程名称
    Baidu IoT Study
    msp430f5438a Information Flash Seg Write -- Chapter
    MFC 编辑框内容更新方法以及滚动条设置
    通过打开按钮打开文件和通过左键移动打开文件并计算crc
    移动文件并将文件路径显示到编辑框内
    Aritronix Virtual Device 运行
    将一个char类型的数转换成曼切斯特数
    数组中重复的数字
    平衡二叉树
  • 原文地址:https://www.cnblogs.com/BLADEVIL/p/3479094.html
Copyright © 2011-2022 走看看