#include <iostream.h>
#include <string.h>
int data[]={40,25,30,20};
int N=4,total=917;
int stack[100],top;
int temp[100],len;
int min;
void print()
{
int i;
for(i=0;i<len;i++)
cout<<temp[i]<<" ";
cout<<endl;
}
int Sum()
{
int i;
int sum=0;
for(i=0;i<top;i++)
sum=sum+data[i]*stack[i];
return sum;
}
void Trackback(int deep)
{
int i;
if(deep>=N)
{
if(total-Sum() < min && top==N)
{
min=total-Sum();
memcpy(temp,stack,sizeof(int)*top);
len=top;
}
return ;
}
for(i=1;i<=total/data[deep];i++)
{
stack[top++]=i;
if(Sum()>total)
{
top--;
return;
}
Trackback(i+1);
top--;
}
}
int main()
{
top=0;
min=total;
Trackback(0);
print();
cout<<"min="<<min<<endl;
return 0;
}
#include <string.h>
int data[]={40,25,30,20};
int N=4,total=917;
int stack[100],top;
int temp[100],len;
int min;
void print()
{
int i;
for(i=0;i<len;i++)
cout<<temp[i]<<" ";
cout<<endl;
}
int Sum()
{
int i;
int sum=0;
for(i=0;i<top;i++)
sum=sum+data[i]*stack[i];
return sum;
}
void Trackback(int deep)
{
int i;
if(deep>=N)
{
if(total-Sum() < min && top==N)
{
min=total-Sum();
memcpy(temp,stack,sizeof(int)*top);
len=top;
}
return ;
}
for(i=1;i<=total/data[deep];i++)
{
stack[top++]=i;
if(Sum()>total)
{
top--;
return;
}
Trackback(i+1);
top--;
}
}
int main()
{
top=0;
min=total;
Trackback(0);
print();
cout<<"min="<<min<<endl;
return 0;
}