• 动态规划——K背包问题


    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
    ");
      else {
       printf("%d
    ",k);
      for(i=0;i<k;i++)
      { if(i!=0)printf(" ");
       printf("%d",b[i]);
      }
       printf("
    ");
      }
     }
     return 0;
    
    }
    View Code
    版权声明:此代码归属博主, 请务侵权!
  • 相关阅读:
    Linux 下动态查找磁盘数量方法
    Laravel 学习 .env文件 getenv 获得环境变量的值
    win10系统怎样手动安装cab更新补丁
    TP框架中模糊查询实现
    PHP函数之HTMLSPECIALCHARS_DECODE
    Tp框架—方法中处理数据
    TP框架I方法详解
    鼠标经过图像改变实现
    TP视图命名规则之一
    Json_decode:详解
  • 原文地址:https://www.cnblogs.com/www-cnxcy-com/p/4727741.html
Copyright © 2020-2023  润新知