题目地址:http://jobdu.sinaapp.com/problem.php?pid=1030
C语言源码:
做法一:DP
#include<stdio.h>
#include<stdlib.h>
int dp[1000];
int max(int a,int b)
{
return a>b?a:b;
}
typedef struct bg
{
int happy;
int last;
int time;
}bg;
bg b[40];
int cmp(const void *a,const void *b)
{
bg *aa=(bg *)a;
bg *bb=(bg *)b;
return aa->time-bb->time;
}
int main()
{
int n,i,p,j;
scanf("%d",&n);
while(n>=0)
{
for(i=1;i<=n;i++)
scanf("%d %d %d",&b[i].happy,&b[i].last,&b[i].time);
qsort(&b[1],n,sizeof(b[0]),cmp);
p=b[n].time;
for(i=0;i<=p;i++)
dp[i]=0;
for(i=1;i<=n;i++)
{
for(j=b[i].time;j>=b[i].last;j--)
dp[j]=max(dp[j],dp[j-b[i].last]+b[i].happy);
for(j=b[i].time;j<=p;j++)
dp[j]=dp[b[i].time];
}
printf("%d\n",dp[p]);
scanf("%d",&n);
}
}
做法二:搜索,注意剪枝
#include<stdio.h>
#include<stdlib.h>
typedef struct bg
{
int happy;
int last;
int time;
}bg;
bg b[41];
int visited[41];
int n,max;
int cmp(const void *a,const void *b)
{
bg *aa=(bg *)a;
bg *bb=(bg *)b;
return aa->time-bb->time;
}
void dfs(int happy,int time)
{
int i=0,top,mark[41];
top=0;
while(i<n)
{
if(visited[i]==0&&(time>=b[i].time||time+b[i].last>b[i].time))
{
mark[top++]=i;
visited[i]=1;
}
i++;
}
i=0;
while(i<n)
{
if(visited[i]==0)
{
visited[i]=1;
if(time+b[i].last<=b[i].time)
dfs(happy+b[i].happy,time+b[i].last);
else
dfs(happy,time);
visited[i]=0;
}
i++;
}
for(i=0;i<top;i++)
visited[mark[i]]=0;
if(happy>max)
max=happy;
}
int main()
{
int i;
scanf("%d",&n);
while(1)
{
if(n<0)
break;
for(i=0;i<n;i++)
scanf("%d %d %d",&b[i].happy,&b[i].last,&b[i].time);
for(i=0;i<n;i++)
visited[i]=0;
qsort(b,n,sizeof(b[0]),cmp);
max=0;
dfs(0,0);
printf("%d\n",max);
scanf("%d",&n);
}
}