zoukankan      html  css  js  c++  java
  • POJ 2576 二维背包

    Tug of War
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 8437   Accepted: 2292

    Description

    A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.

    Input

    The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.

    Output

    Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.

    Sample Input

    3
    100
    90
    200
    

    Sample Output

    190 200
    

    Source

    题目意思:
        一个组有n个人,现在需要把这n个人分成两组,两组的人数的个数相差不超过1,并且使得二组的人的体重之和相差尽可能小;
    解题思路:
       二位背包,nn=(n+1)>>1,sum=sum_weight>>1;在此基础上进行背包;
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<ctime>
     5 #include<algorithm>
     6 #include <map>
     7 #include <queue>
     8 using namespace std;
     9 const int maxn=57;
    10 const int maxs=20500;
    11 bool dp[maxn][maxs];
    12 int weight[107];
    13 int n;
    14 int sum;
    15 int slove()
    16 {
    17     memset(dp,0,sizeof(dp));
    18     dp[0][0]=1;
    19     int ans=0;
    20     int nn=(n+1)>>1;
    21     int sum2=sum>>1;
    22     for(int k=1;k<=n;k++)
    23     for(int i=nn;i>=1;i--)
    24         for(int j=sum2;j>=weight[k];j--)
    25 
    26     {
    27            if(!dp[i][j]) dp[i][j]=dp[i-1][j-weight[k]];
    28            if(dp[i][j]&&j>ans) ans=j;
    29     }
    30 
    31     return ans;
    32 }
    33 int main()
    34 {
    35     while(~scanf("%d",&n)){
    36         sum=0;
    37         for(int i=1;i<=n;i++)
    38         {
    39           scanf("%d",&weight[i]);
    40           sum+=weight[i];
    41         }
    42         int ans=slove();
    43         int ans2=sum-ans;
    44         if(ans>ans2) swap(ans,ans2);
    45         printf("%d %d
    ",ans,ans2);
    46     }
    47 }
  • 相关阅读:
    常用辅助类(ContDownLatch、CyclicBarrier、Semaphore)
    Redis
    SpringBoot
    微服务概述
    数据库 子查询和分页查询
    数据库基础语句,聚合函数,练习
    数据库基础知识

    for循环的类型以及while循环
    C#编程循环练习
  • 原文地址:https://www.cnblogs.com/codeyuan/p/4358046.html
Copyright © 2011-2022 走看看