http://acm.hdu.edu.cn/showproblem.php?pid=1881
dp算法:
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int len,end,happy;
bool operator<(const node &u)
{ return end<u.end;}
}bg[35];
int dp[10000]; //dp [i]表示在i小时的最大快乐度
int max(int a,int b)
{
if(a>b)
return a;
return b;
}
int main()
{
freopen("in.txt","r",stdin);
int i,j,k;
int n;
while(cin>>n&&n>=0)
{
for(i=1;i<=n;i++)
cin>>bg[i].happy>>bg[i].len>>bg[i].end;
int num;
memset(dp,0,sizeof(dp));
sort(bg+1,bg+n+1);
for(i=1;i<=n;i++)
{
num=bg[i].end;
for(j=num;j>=bg[i].len;j--)
{
dp[j]=max(dp[j],dp[j-bg[i].len]+bg[i].happy);
}
}
int ans=0;
for(i=0;i<=num;i++)
ans=max(ans,dp[i]);
cout<<ans<<endl;
}
fclose(stdin);
return 0;
}
搜索算法:
#include<stdio.h>
#include<stdlib.h>
int max,n,sum;
typedef struct Node
{
int h;
int l;
int t;
}Node;
Node no[32];
int cmp(const void *a,const void *b)
{
Node *c=(Node *)a;
Node *d=(Node *)b;
return c->t-d->t;
}
void fun(int a,int time,int ha1,int ha2) //time现在所用的时间,ha1现在的快乐度,ha2是no数组中0到a-1的快乐度之和
{
if(a<n)
{
if(ha1+no[a].h>max && time+no[a].l<=no[a].t)
max=ha1+no[a].h;
if(time>=no[a].t || ha1+sum-ha2<=max)
return;
if(time+no[a].l<=no[a].t)
fun(a+1,time+no[a].l,ha1+no[a].h,ha2+no[a].h);
fun(a+1,time,ha1,ha2+no[a].h);
}
}
int main()
{
int i;
freopen("in.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
if(n<0) break;
max=0;
sum=0;
for(i=0;i<n;i++)
{
scanf("%d%d%d",&no[i].h,&no[i].l,&no[i].t);
sum+=no[i].h;
}
qsort(no,n,sizeof(Node),cmp);
fun(0,0,0,0);
printf("%d/n",max);
}
fclose(stdin);
return 0;
}