• 随机算法 poj 2576 Tug of War


    Tug of War
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 8187   Accepted: 2204

    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


     1 #include <iostream>
     2 #include <string.h>
     3 #include <stdio.h>
     4 #include <math.h>
     5 #include <stdlib.h>
     6 #include <time.h>
     7 using namespace std;
     8 int aabs(int a)
     9 {
    10     if(a>0)return a;
    11     else return -a;
    12 }
    13 int main()
    14 {
    15     int n,a[110][2],b1=0,b0=0,sum0=0,sum1=0,cha,i;
    16     scanf("%d",&n);
    17     srand((unsigned)time(NULL));
    18     for(i=0; i<n; i++)
    19     {
    20         if(i&1)
    21             scanf("%d",&a[1][b1]),sum1+=a[1][b1++];
    22         else scanf("%d",&a[0][b0]),sum0+=a[0][b0++];
    23     }
    24     cha=aabs(sum1-sum0);
    25     n=1000000;
    26     while(n--)
    27     {
    28         int c0=rand()%b0;
    29         int c1=rand()%b1;
    30         if(cha>aabs((sum0-a[0][c0]+a[1][c1])-(sum1-a[1][c1]+a[0][c0])))
    31         {
    32             sum0=sum0-a[0][c0]+a[1][c1];
    33             sum1=sum1-a[1][c1]+a[0][c0];
    34             swap(a[0][c0],a[1][c1]);
    35             cha=aabs(sum0-sum1);
    36         }
    37     }
    38     if(sum0>sum1)swap(sum0,sum1);
    39     cout<<sum0<<" "<<sum1<<endl;
    40 }
    View Code
  • 相关阅读:
    超出范围样式...
    CSS 滚动条设置
    js 数组全包含
    vue字段为空过滤器
    window.open 打开的新页签会携带sessionStorage中的数据
    ES6的解构赋值与深拷贝和浅拷贝
    vue中怎么处理多个单选框,且单选框互不影响的方案
    h5项目中关于ios手机软键盘导致页面变形的完美解决方案
    vue项目中关于微信分享的坑,以及安卓和ios获取location.href不同的处理
    navicat连接mysql报错1251的解决方法
  • 原文地址:https://www.cnblogs.com/ERKE/p/3830408.html
Copyright © 2020-2023  润新知