poj 3140 Contestants Division 夜

http://poj.org/problem?id=3140

一遍DFS 枚举任一条边被切断的情况就可以

代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<cmath>
#include<stack>
#include<algorithm>
#define LL long long

using namespace std;

const int N=100005;
struct node
{
    LL sum;
    struct tt *next;
}mem[N];
struct tt
{
    int j;
    struct tt *next;
};
LL ans,All;
int a[N];
void build(int i,int j)
{
    struct tt *t=new tt;
    t->j=j;
    t->next=mem[i].next;
    mem[i].next=t;
}
void Dele(int n)
{
    for(int i=1;i<=n;++i)
    {
        mem[i].next=NULL;
    }
}
void updateans(LL k)
{
    LL k1=All-k;
    if(k<k1)
    swap(k,k1);
    if(k-k1<ans)
    ans=k-k1;
}
LL dfs(int x,int pre)
{
    struct tt *t=mem[x].next;
    mem[x].sum=a[x];
    while(t!=NULL)
    {
        if(t->j!=pre)
        {
            mem[x].sum+=dfs(t->j,x);
        }
        t=t->next;
    }
    updateans(mem[x].sum);
    return mem[x].sum;
}
int main()
{
    int n,m;
    int I=0;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        ++I;
        if(n==0&&m==0)
        break;
        All=0;
        for(int i=1;i<=n;++i)
        {
            scanf("%d",&a[i]);
            All+=a[i];
        }
        while(m--)
        {
            int x,y;
            scanf("%d %d",&x,&y);
            build(x,y);
            build(y,x);
        }
        ans=All;
        dfs(1,-1);
        printf("Case %d: ",I);
        cout<<ans<<endl;
        Dele(n);
    }
}

  

原文地址:https://www.cnblogs.com/liulangye/p/2605535.html