zoukankan      html  css  js  c++  java
  • [swustoj 785] Divide Tree

    Divide Tree(0785)

    问题描述

    As we all know that we can consider a tree as a graph. Now give you a tree with nodes having its weight. We define the weight of a tree is the sum of the weight of all nodes on it. You know we can divide the tree into two subtrees by any edge of the tree. And your task is to tell me the minimum difference between the two subtrees’ weight.

    输入

    The first line, an integer T (T <= 30), representing T test cases blew.

    For each test case, the first line contains one integer N (2 <= N <= 10000), indicating the number of tree’s nodes. Then follow N integers in one line, indicating the weight of nodes from 1 to N.

    For next N-1 lines, each line contains two integers Vi and Vj (1 <= Vi, Vj <= N), indicating one edge of the tree.

    输出

    For each test case, output the minimum weight difference. We assume that the result will not exceed 2^20.

    样例输入

    1
    5
    6 3 9 3 1
    2 3
    3 1
    4 1
    1 5

    样例输出

    20

    简单题

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<vector>
    #include<cmath>
    using namespace std;
    #define min(a,b) ((a)<(b)?(a):(b))
    #define INF 0x3f3f3f3f
    #define pb push_back
    #define N 10010
     
    int n;
    int ans;
    int val[N];
    int size[N];
    vector<int> edge[N];
     
     
    void init()
    {
        ans=INF;
        for(int i=1;i<=n;i++){
            edge[i].clear();
            size[i]=0;
        }
    }
    void dfs1(int u,int pre)
    {
        size[u]=val[u];
        for(int i=0;i<edge[u].size();i++){
            int v=edge[u][i];
            if(v!=pre){
                dfs1(v,u);
                size[u]+=size[v];
            }
        }
    }
    void dfs2(int u,int pre)
    {
        for(int i=0;i<edge[u].size();i++){
            int v=edge[u][i];
            if(v!=pre){
                ans=min(ans,abs((size[1]-size[v])-size[v]));
                dfs2(v,u);
            }
        }
    }
    int main()
    {
        int T;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d",&n);
            init();
            for(int i=1;i<=n;i++){
                scanf("%d",&val[i]);
            }
            for(int i=1;i<n;i++){
                int a,b;
                scanf("%d%d",&a,&b);
                edge[a].pb(b);
                edge[b].pb(a);
            }
            dfs1(1,1);
            dfs2(1,1);
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    shell基础--变量的数值计算
    shell基础--字符串和变量的操作
    shell基础--shell特殊变量
    Asp.net MVC 控制器扩展方法实现jsonp
    ASP.NET web api 跨域请求
    asp.net Web API简单的特性路由配置
    ASP.Net Web API 输出缓存 转载 -- Output caching in ASP.NET Web API
    基础拾遗 C# Json 与对象相互转换
    内存溢出和内存泄漏
    软件测试面试题(一)
  • 原文地址:https://www.cnblogs.com/hate13/p/4605223.html
Copyright © 2011-2022 走看看