您的位置:首页 > 其它

贪心 简单背包问题

2013-11-15 22:02 441 查看
背包问题的基本描述是: 有一个背包,能盛放的物品总重量为S,设有N件物品,其重量分别为w1,w2,...,wn.希望从N件物品中选择若干件物品,所选物品的重量之和恰能放入该背包,即所选物品的重量之和等于S。

程序1:递归算法

#include <stdio.h>
#include <stdlib.h>
int w[100];
int knap(int s,int n)
{
if(s==0)return 1;
if(s<0||(s>0&&n<1))return 0;
if(knap(s-w
,n-1))
{
printf("%d",w
);
return 1;
}
return knap(s,n-1);
}
int main()
{
int S,N,i;
while(~scanf("%d %d",&S,&N))
{
for(i=1;i<=N;i++)
scanf("%d",&w[i]);
if(knap(S,N))
printf("yes!\n");
else printf("no!\n");
}
return 0;
}

#include <iostream>
#include <stdlib.h>

using namespace std;

const int N=7;
const int S=20;
int w[N+1]={0,1,4,3,4,5,2,7};

int knap(int s,int n)
{
if(s==0)return 1;
if(s<0||(s>0&&n<1))return 0;
if(knap(s-w
,n-1))
{
cout<<w
;
return 1;
}
return knap(s,n-1);
}

int main(int argc, char *argv[])
{
if(knap(S,N))cout<<endl<<"OK"<<endl;
else cout<<"NO"<<endl;
system("PAUSE");
return 0;
}

程序2:非递归算法

#include <iostream>
#include <stdlib.h>

using namespace std;

const int N=7;
const int S=20;
int w[N+1]={0,1,4,3,4,5,2,7};

typedef struct{
int s;
int n;
int job;
}KNAPTP;

int knap(int s,int n)
{
KNAPTP stack[100],x;
int top,k,rep;
x.s=s;
x.n=n;
x.job=0;
top=1;
stack[top]=x;
k=0;
while(k==0&&top>0){
x=stack[top];
rep=1;
while(!k&&rep){
if(x.s==0)k=1;
else if(x.s<0||x.n<=0)rep=0;
else {
x.s=x.s-w[x.n--];
x.job=1;
stack[++top]=x;
}
}
if(!k){
rep=1;
while(top>=1&&rep){
x=stack[top--];
if(x.job==1){
x.s+=w[x.n+1];
x.job=2;
stack[++top]=x;
rep=0;
}
}
}
}
if(k){
while(top>=1){
x=stack[top--];
if(x.job==1)cout<<w[x.n+1];
}
}
return k;
}
int main(int argc, char *argv[])
{
if(knap(S,N))cout<<endl<<"OK"<<endl;
else cout<<"NO"<<endl;
system("PAUSE");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: