#include<stdio.h>
#define len 10
main()
{
int m[len];
int num[len]={0};
int n,j;
int i=0;
int temp=1;
printf("please input the vertex:\n");
printf("if you want to end inputing,please input 0\n");
while(i<len&&temp!=0)
{
scanf("%d",&temp);
if(temp!=0)
m[i]=temp;
i++;
if(judgeorder(m)==0)
{
printf("please reenter the vertex:\n");
for(j=0;j<=i;j++)
m[j]=0;
i=0;
}
}
printf("please input the amount of money:\n");
scanf("%d",&n);
i=0;
while(m[i]!=0)
{
num[i]=n/m[i];
n=n-num[i]*m[i];
if(n==0)
break;
i++;
}
for(i=0;i<len;i++)
{
if(num[i]==0)
continue;
else
printf("The %3d fen needs %3d\n",m[i],num[i]);
}
getch();
}
int judgeorder(int a[len])
{
int i,count=0;
for(i=0;i<len-1&&a[i]!=0;i++)
{
if(a[i]<a[i+1])
{
return 0;
break;
}
else count++;
}
if(count==len-2)
return 1;
}
找零钱问题:以人民币1元,2元,5元,10元,20元,50元,100元为例,要求所找的张数最少
#include<stdio.h>
#include<memory.h>
int a[2000],b[200000],n,m,i,j;
int main()
{
scanf("%d",&n);//钱币种类
for (i=0;i<n;i++)
scanf("%d",&a[i]);//每个钱币的面值
scanf("%d",&m);//需要计算的钱币的面值
memset(b,0,sizeof(b));
for (i=0;i<n;i++)
b[a[i]]=1;
for (i=1;i<=m;i++)
for (j=0;j<n;j++)
if (i-a[j]>0)
if (b[i]==0)
{
if (b[i-a[j]]!=0)
b[i]=b[i-a[j]]+1;
}
else
{
if (b[i-a[j]]!=0&&b[i-a[j]]+1<b[i])
b[i]=b[i-a[j]]+1;
}
if (b[m]==0) printf("-1\n");//找不开输出-1
else printf("%d\n",b[m]);//可以找到交换策略,输出最小票数
return 0;
}
求找零钱问题和背包贪心算法问题(背包里物体可分解)C语言程序悬赏分:20 - 解决时间:2007-6-9 00:05找零钱问题:以人民币1元,2元,5元,10元,20元,50元,100元为例,要求所找的张数最少 背包问题:假设物体重量W1,W2...Wn其对应的价值为P1,P2...Pn,物体可分割,第一题: #include<stdio.h> #include<memory.h> int a[2000],b[200000],n,m,i,j; int main() { scanf("%d",&n);//钱币种类 for (i=0;i<n;i++) scanf("%d",&a[i]);//每个钱币的面值 scanf("%d",&m);//需要计算的钱币的面值 memset(b,0,sizeof(b)); for (i=0;i<n;i++) b[a[i]]=1; for (i=1;i<=m;i++) for (j=0;j<n;j++) if (i-a[j]>0) if (b[i]==0) { if (b[i-a[j]]!=0) b[i]=b[i-a[j]]+1; } else { if (b[i-a[j]]!=0&&b[i-a[j]]+1<b[i]) b[i]=b[i-a[j]]+1; } if (b[m]==0) printf("-1\n");//找不开输出-1 else printf("%d\n",b[m]);//可以找到交换策略,输出最小票数 return 0; } 第二题: #include<iostream> #include<algorithm> using namespace std; struct good//表示物品的结构体 { double p;//价值 double w;//重量 double r;//价值与重量的比 }a[2000]; double s,value,m; int i,n; bool bigger(good a,good b) { return a.r>b.r; } int main() { scanf("%d",&n);//物品个数 for (i=0;i<n;i++) { scanf("%lf%lf",&a[i].w,&a[i].p); a[i].r=a[i].p/a[i].w; } sort(a,a+n,bigger);//调用sort排序函数,你大概不介意吧,按照价值与重量比排序贪心 scanf("%lf",&m);//读入包的容量m s=0;//包内现存货品的重量 value=0;//包内现存货品总价值 for (i=0;i<n&&s+a[i].w<=m;i++) { value+=a[i].p; s+=a[i].w; } printf("The total value in the bag is %.2lf.\n",value);//输出结果 return 0; }http://zhidao.baidu.com/question/27358823.html?fr=ala0http://wenwen.soso.com/z/q32660486.htm#include<stdio.h> main() { int money,n,a,b,c,d,e,f,g,h,i,j,k,l; printf("请输入钱数:"); scanf("%d",&money); a=money/100; b=money%100; c=b/50; d=b%50; e=d/20; f=d%20; g=f/10; h=f%10; i=h/5; j=h%5; k=j/2; l=j%2; n=a+c+e+g+i+k+l; printf("钞票的最少张数是:"); printf("%d\n",n); }