poj3140

/*
分析:
    1Y,水,只能说比赛的时候想多了。。。
    树形dp,甚至说dp都算不上。
    给的是一棵树,枚举每条边被删掉,计算两边的差就行了,
因为是树,所以这个枚举很easy了就。。
    比赛的时候题意读的不是太懂,具体意思是我yy出来的,不
是很确定,就放那儿研究别的题去了,鸟语不行桑不起呀囧~

                                                        2013-05-08
*/






#include"iostream"
#include"cstdio"
#include"cstring"
using namespace std;
const int N=100011;

int n,m,val[N],hash[N];
__int64 sum,dp[N];

struct Edge{
    int v,next;
}edge[N],edge_pre[20*N];
int tot,head[N],tot_pre,head_pre[N];
void add(int a,int b){
    edge[tot].v=b;edge[tot].next=head[a];head[a]=tot++;
}
void add_pre(int a,int b){
    edge_pre[tot_pre].v=b;edge_pre[tot_pre].next=head_pre[a];head_pre[a]=tot_pre++;
}

void dfs1(int k)
{
    int j,v;
    for(j=head_pre[k];j!=-1;j=edge_pre[j].next)
    {
        v=edge_pre[j].v;
        if(hash[v]) continue;
        hash[v]=1;
        add(k,v);
        dfs1(v);
    }
}
void build_map()
{
    int a,b;

    tot_pre=0;
    memset(head_pre,-1,sizeof(head_pre));
    while(m--)
    {
        scanf("%d%d",&a,&b);
        add_pre(a,b);
		add_pre(b,a);
    }
    memset(hash,0,sizeof(hash));
    hash[1]=1;
    tot=0;
    memset(head,-1,sizeof(head));
    dfs1(1);
}
void dfs2(int k)
{
    int j,v;
    dp[k]+=val[k];
    for(j=head[k];j!=-1;j=edge[j].next)
    {
        v=edge[j].v;
        dfs2(v);
        dp[k]+=dp[v];
    }
}
int main()
{
    int i,Case=1;
    while(scanf("%d%d",&n,&m),n,m)
    {
        sum=0;
        for(i=1;i<=n;i++)   {scanf("%d",&val[i]);sum+=val[i];}
        build_map();
        memset(dp,0,sizeof(dp));
        dfs2(1);
        __int64 temp,ans=sum;
        for(i=2;i<=n;i++)
        {
            temp=sum-dp[i]-dp[i];
			if(temp<0)		temp*=-1;
            if(temp<ans)    ans=temp;
        }
        printf("Case %d: %I64d\n",Case++,ans);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值