码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划——K背包问题

时间:2015-08-13 17:45:41      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description
Now you are asked to measure a dose of medicine with a balance and a number of weights. Certainly it is not always achievable. So you should find out the qualities which cannot be measured from the range [1,S]. S is the total quality of all the weights.
Input
The input consists of multiple test cases, and each case begins with a single positive integer N (1<=N<=100) on a line by itself indicating the number of weights you have. Followed by N integers Ai (1<=i<=N), indicating the quality of each weight where 1<=Ai<=100.
Output
For each input set, you should first print a line specifying the number of qualities which cannot be measured. Then print another line which consists all the irrealizable qualities if the number is not zero.
Sample Input


3
1 2 4  
3  
9 2 1


Sample Output


0
2  
4 5

解题思路:

用天平称重时,可以有两种方法。一种是砝码和物体分别放在两侧;

另一种是砝码和物体放在同一侧,另一侧再放砝码,此时和物体在同一侧的砝码相当于是负重量,这是本题的关键

首先,砝码重量可能相等,要统计各自的数量

然后再套用母函数

最后,统计不能称量的

程序代码:

技术分享
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define W 10005
using namespace std;
int b[W],c[W];
int main()
{
 int a[105],d[105];
 int N,i,t,n,j,len,r,p,k;
 while(scanf("%d",&N)!=EOF)
 {
  for(i=0;i<N;i++)
  scanf("%d",&a[i]);
  sort(a,a+N);
  d[0]=t=a[0];n=1;j=0;
  for(i=1;i<N;i++)
  {
   if(a[i]==t){n++;}
   else {d[j]=n;n=1;a[j++]=t;t=a[i];}
  }
  a[j]=t;
  d[j]=n;
  memset(b,0,sizeof(b));
  memset(c,0,sizeof(c));
  for(i=0;i<=d[0]*a[0];i+=a[0])
   c[i]=1;len=d[0]*a[0];
  for(i=1;i<=j;i++)
  {
   for(p=0;p<=len;p++)
   for(k=0;k<=d[i]*a[i];k+=a[i])
   {
    b[p+k]+=c[p];
       if(k!=0&&p!=0)
        {r=fabs(p-k);
    b[r]+=c[p];}
   }
   len+=d[i]*a[i];
   for(k=0;k<=len;k++)
   {c[k]=b[k];b[k]=0;}
  }
  n=0;
  for(i=1,k=0;i<=len;i++)                       
  if(c[i]==0) b[k++]=i;
  if(k==0)printf("0\n");
  else {
   printf("%d\n",k);
  for(i=0;i<k;i++)
  { if(i!=0)printf(" ");
   printf("%d",b[i]);
  }
   printf("\n");
  }
 }
 return 0;

}
View Code

 

动态规划——K背包问题

标签:

原文地址:http://www.cnblogs.com/www-cnxcy-com/p/4727741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!