zoukankan      html  css  js  c++  java
  • 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);
        }
    }
    

      

  • 相关阅读:
    Java 对文件的操作
    快速排序算法
    Java 时间和字符换的处理
    Redis 数据结构之Keys
    [转] Redis系统性介绍
    【转】JAVA 接口
    [转] Python 代码性能优化技巧
    几道关于面试的题目
    随手笔记2
    随手笔记
  • 原文地址:https://www.cnblogs.com/liulangye/p/2605535.html
Copyright © 2011-2022 走看看