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.
  • 相关阅读:
    Confluence 6 创建你的个人空间
    Win10正式专业版激活方法
    还在手工写接口测试文档,已经out了
    MYSQL支持的数据类型-数值类型
    mysql
    转 聊聊连接池和线程
    当压测数据压不上去时可能是哪些原因造成的
    IDEA自动导包(全局设置)
    微服务化后缓存怎么做
    win10家庭版升级到专业版密钥
  • 原文地址:https://www.cnblogs.com/BLADEVIL/p/3479094.html
Copyright © 2011-2022 走看看