hdoj 1587(背包问题)(我利用动态规划完成)

来源:互联网 发布:mac apache ant 安装 编辑:程序博客网 时间:2024/05/22 13:24
#include<iostream>#include<stdio.h>using namespace std;#define MAX 1000//#define MAX 1000class Point{public:int flower;int cost;};int N,M;int collect[MAX][MAX];int money[MAX];//每一种花花多少钱void init(){int i,j;for(i=0;i<MAX;i++)for(j=0;j<MAX;j++)collect[i][j]=-1;}int dp(Point p){//如果访问过if(collect[p.flower][p.cost]!=-1){return collect[p.flower][p.cost];}//如果到达最大限度if(p.cost==M){collect[p.flower][p.cost]=p.flower;return collect[p.flower][p.cost];}int tmax=-1;int i=0;Point cs;for(i=0;i<N;i++){cs.flower=p.flower+1;cs.cost=p.cost;cs.cost+=money[i];if(cs.cost>M)continue;int fmax=dp(cs);if(tmax<fmax)tmax=fmax;}if(tmax==-1)//如果没有买花{tmax=p.flower;}collect[p.flower][p.cost]=tmax;return collect[p.flower][p.cost];}int main(){//freopen("in.txt","r",stdin);while(scanf("%d %d",&N,&M)!=EOF){//初始化init();int i=0;//输入钱for(i=0;i<N;i++){scanf("%d",&money[i]);}//处理Point start;start.cost=0;start.flower=0;int result=dp(start);//输出cout<<result<<endl;}return 0;}

原创粉丝点击