#pragma comment(linker, "/STACK:1024000000,1024000000") //加栈
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
using namespace std;
typedef long long ll;
const int maxn = 1e5+8;
#define inf 1e18+4
vector<int> g[maxn];
int n,m;
ll h[maxn];
ll dp[maxn];
ll ans2;
ll ans;
void dfs(int u,int pre)
{
dp[u]=h[u];
for(int i=0;i<g[u].size();i++)
{
int v=g[u][i];
if(v==pre) continue;
dfs(v,u);
dp[u]+=dp[v];
}
//if(u!=1)
//{
ll M=0;
if(ans-2*dp[u]>0)
{
M=ans-2*dp[u];
}
else
{
M=-(ans-2*dp[u]);
}
ans2=min(ans2,M);
// }
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int Case=0;
while(scanf("%d%d",&n,&m)!=EOF&&(n+m))
{
memset(dp,0,sizeof(dp));
ans=0,ans2=inf;
for(int i=1;i<=n;i++)
{
g[i].clear();
scanf("%lld",&h[i]);
ans+=h[i];
}
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1,0);
printf("Case %d: %lld\n",++Case,ans2);
}
return 0;
}
Contestants Division POJ - 3140 (简单树形dp)
最新推荐文章于 2020-03-15 22:51:32 发布