hdu 1074 Doing Homework(状态压缩dp)


hdu 1074 Doing Homework


当前阶段的状态从上一阶段的状态推出


#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
#define INF 0x7ffffff
#define MAXN 1<<16
struct node
{
	char name[105];
	int dt,cost;
}hw[20];
stack<int> out;
int dp[MAXN],used[MAXN],path[MAXN],n;
int min(int a,int b) {return a<b?a:b;}
void dfs(int stu)
{
	if(stu>=(1<<n)) return ;
	for(int i=0;i<n;i++)
		if(stu&(1<<i))
		{
			int t=used[stu^(1<<i)]+hw[i].cost>hw[i].dt?
				used[stu^(1<<i)]+hw[i].cost-hw[i].dt:0;
			if(dp[stu^(1<<i)]+t<=dp[stu])
			{
				dp[stu]=dp[stu^(1<<i)]+t;
				used[stu]=used[stu^(1<<i)]+hw[i].cost;
				path[stu]=stu^(1<<i);
			}
		}
	dfs(stu+1);
}
int main()
{
	int cas;
	scanf("%d",&cas);
	while(cas--)
	{
		scanf("%d",&n);
		for(int i=0;i<n;i++)
			scanf("%s%d%d",hw[i].name,&hw[i].dt,&hw[i].cost);
		for(int i=0;i<(1<<n);i++) dp[i]=INF;
		dp[0]=used[0]=0;
		dfs(1);
		printf("%d\n",dp[(1<<n)-1]);
		int pre=(1<<n)-1;
		for(int i=0;i<n;i++)
		{
			int t=pre;
			t=t^path[pre];
			pre=pre^t;
			int pos=-1;
			while(t)
			{
				if(t&1)
				{
					pos++;
					break;
				}
				t>>=1;
				pos++;
			}
			out.push(pos);
		}
		while(!out.empty())
		{
			printf("%s\n",hw[out.top()].name);
			out.pop();
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值