hdu1881搜索与dp

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值