0
点赞
收藏
分享

微信扫一扫

完全背包--暴力枚举

和谐幸福的人生 2022-04-06 阅读 50
算法c++

 

#include<iostream>
using namespace std;

//这道题目我的思路就是枚举,把100元的,50元的,20元的,10元的全部写一遍,只要总和是n,就让count++。 

int main()
{
 int n,count=0;//count方案数目,初始为0. 
 cin>>n;//输入一个n,代表一共多少钱 
 for(int i=0;i<=n;i+=100)//一百元的 
 {
  for(int j=0;j<=n;j+=50)//五十元的 
     {
      for(int l=0;l<=n;l+=20)//二十元的 
        {
         for(int m=0;m<=n;m+=10)//十元的 
             {
              if(m+l+j+i==n)//加起来等于n的 
              {
                        cout<<i<<" "<<j<<" "<<l<<" "<<m<<endl;//输出多少种方案,记得改行可以注释。建议样例为100. 
               count++;//方案加一 
              }
             }
         }
     }
 }
 cout<<count;
}

第二种做法

#include<stdio.h>

int main(void){
 int n,m=0;
 scanf("%d",&n);
 int i,j,k,l;
 for(i=0;i*100<=n;i++){
  for(j=0;j*50<=n;j++){
   for(k=0;k*20<=n;k++){
    for(l=0;l*10<=n;l++){
     if(i*100+j*50+k*20+l*10==n){
      m++;
     }
    }
   }
  }
 }
 printf("%d",m);
 return 0;
} 
举报

相关推荐

0 条评论