2008年第5题

题目地址: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);
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值