题目:http://poj.org/problem?id=3140
题意:给你一棵树,让你找一条边,使得两颗子树权值和相差最小,求最小的权值差
思路:直接树dp,找树权值和sum和2*子树权值和的最小差值就行了
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<vector>
using namespace std;
typedef long long ll;
const int N = 1e6+5;
struct edge
{
int to,nxt;
edge(int t = 0,int n = 0):to(t),nxt(n){}
}E[N*2];
int n,m,a[N],tot,head[N*2];
ll dp[N],minn,sum;
void add_edge(int u,int v)
{
E[tot] = edge(v,head[u]);
head[u] = tot++;
}
void dfs(int u,int fa)
{
dp[u] = a[u];
for(int i = head[u];~i;i = E[i].nxt)
{
int v = E[i].to;
if(v == fa)
continue;
dfs(v,u);
dp[u] += dp[v];
}
minn = min(minn,llabs(sum-2*dp[u]));
}
int main()
{
int ca = 0;
while(~scanf("%d%d",&n,&m) && (n || m))
{
tot = 0;
memset(head,-1,sizeof(head));
sum = 0;
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]),sum += a[i];
int u,v;
while(m--)
{
scanf("%d%d",&u,&v);
add_edge(u,v);
add_edge(v,u);
}
minn = 1e13;
memset(dp,0,sizeof(dp));
dfs(1,-1);
printf("Case %d: %lld\n",++ca,minn);
}
return 0;
}