ACM: 动态规划题+剪枝 toj 3904

                  Points cakes

描述

 

A mother has n different sizes of cake,she wants to give to his two children by a fair way(which may not completely average, but requires minimum), 

you can help she solve this problem?

输入

 

there are many case of testdata,for each testdata,

first line: an integer n(3<=n<=1000), means how many cakes does the mother has.

second line: n integers, for each a[i](1<=a[i]<=50), a[i] means the size of ith cake.

输出

 

for each teatdata, output two integers x, y(x<=y)

x, y means how many cakes do the two children have.

样例输入

3
1 2 3

样例输出

3 3

题意: 分配蛋糕, 有n块不同大小的蛋糕, 要求分配给两个人, 如果不可以实现分配均匀(重量相同分配).

      尽量达到大小相近.

解题思路:

        1. 动态规划: 决策1: 使用当前块, w+a[i] <= sum_half; ==> DP(w+a[i],i+1);

                     决策2: 不使用当前块, 直接跳过. DP(w,i+1);

        2. 纠结一天问题: (1).递归出口是 i == n+1; (一开始忽略了最后一块i==n是错误的)

                         (2).剪枝: if(i == n+1 || maxt == sum_half) 递归出口增加.

                                   已经满足条件的不需要再将递归树伸展了. (TLE解决)

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
#define MAX 1005

int n;
int a[MAX];
int maxt, sum;
int sum_half;

void DP(int w,int reLen)
{
 if(reLen == n+1 || maxt == sum_half)
 {
  if(maxt < w && w <= sum_half) maxt = w;
  return ;
 }
 if(w+a[reLen] <= sum_half) DP(w+a[reLen],reLen+1);
 DP(w,reLen+1);
}

int main()
{
 int i, j;
// freopen("input.txt","r",stdin);
 while(scanf("%d",&n) != EOF)
 {
  sum = 0;
  for(i = 1; i <= n; ++i)
  {
   scanf("%d",&a[i]);
   sum += a[i];
  }
  maxt = 0;
  sum_half = (sum%2==0 ? sum/2 : sum/2+1);
  DP(0,1);
  int big = (maxt > sum-maxt ? maxt : sum-maxt);
  printf("%d %d\n",sum-big,big);
 }

 return 0;
}

                      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值