Topic
to the N-node with the right tree, delete one side, it will become two subtrees,
The absolute minimum of the difference between the weights of these two subtrees is obtained by deleting an edge.
Ideas
Direct DFS once, calculate sum of all subtree weights tot[i]
If you delete an edge (V, FA), FA is the Father node of V,
Then the sum of the V-tree weights is tot[v], and obviously the sum of the weights of another Shang tree is sum-tot[v],
The minimum absolute value can be obtained.
You should pay attention to this problem with long long
In fact, is the Dfs+ enumeration, why would someone put this problem as a tree DP?
Code
/**===================================================== * is a solution for ACM/ICPC problem * * @source: POJ -3140 Contestants Division * @description: Tree DP, counting problem * @author: Shuangde * @blog: blog.csdn.net/shuangde800 * @email:
zengshuangde@gmail.com * Copyright (C) 2013/08/31 14:45 All rights reserved. *======================================================*/#include <iostream> #include <cstdio> # Include <algorithm> #include <vector> #include <queue> #include <cmath> #include <cstring
> Using namespace std;
typedef long long Int64;
const int INF = 0X3F3F3F3F;
const int MAXN = 100010; namespace ADJ {int size, HEAD[MAXN]; struct node{int V, Next;}
E[MAXN*2];
inline void Initadj () {size = 0; memset (head,-1, sizeof (head));} inline void Addedge (int u, int v) {e[size].v = v;
E[size].next = Head[u];
Head[u] = size++;
The using namespace Adj;
int n, m;
int NUM[MAXN];
Int64 ans, sum;
http://www.bianceng.cn
Int64 Abs (Int64 a) {return a<0?-a:a;} Int64 DFS (int u, int fa) {Int64 tot = Num[u]; for (int e = head[u]; e!=-1; e = e[e].next) {int v = e[e].v; if (v
= = FA) continue;
Tot + = DFS (v, u);
ans = min (ans, Abs (Sum-tot-tot));
return tot; int main () {int cas = 1 while (~scanf ("%d%d", &n, &m) && n + m) {sum = 0; i = 1; I <= N;
++i) {scanf ("%d", &num[i]); sum = = Num[i];
Initadj ();
for (int i = 0; i < m; ++i) {int u, v scanf ("%d%d", &u, &v); Addedge (U, v); Addedge (v, u);}
ans = sum;
DFS (1,-1);
cout << "Case" << cas++ << ": << ans << Endl;}
return 0; }