子集树变式问题

来源:互联网 发布:python read 长度 编辑:程序博客网 时间:2024/06/04 17:53

            题目描述:公司发了某商店的购物券1000元,限定只能购买店中的m种商品。每种商品的价格分别为m1,m2,.....,要求程序列出所有的正好能消费完该购物券的不同购物方法。

           程序输入:

           第一行是一个整数m,代表可购买的商品的种类数。

           接下来是m个整数,每个一行,分别代表着m种商品的单价

           程序输出:

           第一行是一个整数,表示共有多少种方案。

           第二行开始,每种方案占一行,表述对每种商品购买的数量,中间用空格分隔。

  例如:

               输入:

              2

              200

              300

             则应输出:

             2

             2   2

             5   0

                                                                                                                                                              ----题目出自    第二届全国软件专业人才设计与开发大赛  选拔赛

           我的代码如下:

#include <stdio.h>#include <conio.h>#define SUM_MONEY 1000#define MAX 1000//global variablesint m=0;//the number of the kindsint price[MAX]={0};//the price of all the kindsint num[MAX]={0};//the max number of one kind goodint count=1;//the number of methodsint c_sum=0;//current sum priceint result[MAX][MAX]={0};//the result number of each kind good//int visited[MAX]={0};//prototypesvoid back_money(int n);//n is the number of pliesint main(){int i=0;printf("Please input the number of the goods:");scanf("%d",&m);for(i=1;i<=m;i++){printf("Please input the price of %d: ",i);scanf("%d",&price[i]);num[i]=SUM_MONEY/price[i];}back_money(1);printf("the number is :%d\n",count-1);for(i=1;i<count;i++){for(int x=1;x<=m;x++){printf("%d ",result[i][x]);}printf("\n");}getch();}void back_money(int n)//n is the number of plies{int j=1;if(c_sum==SUM_MONEY){count++;for(int temp=1;temp<=m;temp++)result[count][temp]=result[count-1][temp];return ;}if(n>m)return;for(j=0;j<=num[n];j++){if(c_sum+price[n]<=SUM_MONEY){//visited[j]=1;c_sum+=price[n]*j;result[count][n]=j;back_money(n+1);result[count][n]=0;//visited[j]=0;c_sum-=price[n]*j;}}}



原创粉丝点击