题目链接:http://poj.org/problem?id=3140
思路:简单树形dp题,dp[u]表示以u为根的子树的人数和。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<climits>
#include<algorithm>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<list>
using namespace std;
#define MAXN 111111
#define inf 1<<30
#define INF 1LL<<60
typedef long long ll;
typedef pair<int,int>PP;
template<class T> inline T Get_MIN(const T &a,const T &b){ return a < b ? a : b; }
template<class T> inline T Get_MAX(const T &a,const T &b){ return a > b ? a : b; }
template<class T> inline T ABS(const T &a){ return a < ? -a : a; } struct Edge{
int v,next;
}edge[MAXN<<]; int n,m,NE;
int head[MAXN]; void Insert(int u,int v)
{
edge[NE].v=v;
edge[NE].next=head[u];
head[u]=NE++;
} ll dp[MAXN],sum,MIN;
void dfs(int u,int father)
{
for(int i=head[u];i!=-;i=edge[i].next){
int v=edge[i].v;
if(v==father)continue;
dfs(v,u);
dp[u]+=dp[v];
}
MIN=Get_MIN(MIN,ABS((dp[u]-(sum-dp[u]))));
// cout<<u<<"**"<<dp[u]<<"****"<<abs(sum-dp[u])<<"**"<<MIN<<endl;
} int main()
{
int u,v,t=;
while(~scanf("%d%d",&n,&m)&&(n||m)){
NE=;
memset(head,-,sizeof(head));
sum=;
for(int i=;i<=n;i++)scanf("%lld",&dp[i]),sum+=dp[i];
while(m--){
scanf("%d%d",&u,&v);
Insert(u,v);
Insert(v,u);
}
MIN=INF;
dfs(,-);
printf("Case %d: %lld\n",t++,MIN);
}
return ;
}