【TLE与否】10123UVa不要歪——记忆化的重要性

参考了 http://www.cnblogs.com/staginner/archive/2011/12/21/2295362.html  (他真是大神),然后自己写了一下。

如果不用记忆化记下 行不通的状态转移路径(rest[st] == 0),就会超时!!!

超时代吗:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int MAXD = 1100000;
int bdlen, bdwt, num;
int pos[30];
int wt[30];
//rest:obj that are not chosen yet; a COMPLEMATARY set of the objects on board
//int rest[MAXD]; 
//-1: not visited yet
//0: can't reach empty state from here, 1:can reach empty state from here
int dfs(int st, int left, int right) //put objects on board one by one
{
	if(st == 0)
		return 1;
	int l, r;
	for(int i = 0; i < num; ++i)
	{
		if(st & (1<<i))
		{
			l = left + (pos[i]+3)*wt[i];
			r = right + (pos[i]-3)*wt[i];
			if(l >= 0 && r <= 0)
			{
				if(dfs(st^(1<<i), l, r))
				{
					//rest[st] = 1;
					printf("%d %d\n", pos[i]/2, wt[i]);
					return 1;
				}
			}
		}
	}
	return  0;
}
int main()
{
	//
	freopen("input.txt", "r", stdin);
	int numcase = 1;
	while(scanf("%d%d%d", &bdlen, &bdwt, &num) == 3 && (bdlen+bdwt+num))
	{
		for(int i = 0; i < num; ++i)
		{
			scanf("%d%d", &pos[i], &wt[i]);
			pos[i] *= 2;
		}
		//memset(rest, -1, sizeof(rest));

		//rest[0] = 1;   //a legal final state; nothing left
		
		printf("Case %d:\n", numcase++);
		if(!dfs((1<<num)-1, 3*bdwt, -3*bdwt))
		{
			printf("Impossible\n");
		}
	}
}

不超时代码(0.000s):

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int MAXD = 1100000;
int bdlen, bdwt, num;
int pos[30];
int wt[30];
//rest:obj that are not chosen yet; a COMPLEMATARY set of the objects on board
int rest[MAXD]; 
//-1: not visited yet
//0: can't reach empty state from here, 1:can reach empty state from here
int dfs(int st, int left, int right) 
{
	if(rest[st] != -1)
		return rest[st];
	int l, r;
	for(int i = 0; i < num; ++i)
	{
		if(st & (1<<i))
		{
			l = left + (pos[i]+3)*wt[i];
			r = right + (pos[i]-3)*wt[i];
			//put objects on board one by one
			if(l >= 0 && r <= 0)
			{
				if(dfs(st^(1<<i), l, r))
				{
					rest[st] = 1;
					printf("%d %d\n", pos[i]/2, wt[i]); 
					return 1;
				}
			}
		}
	}
	return rest[st] = 0;
}
int main()
{
	//
	freopen("input.txt", "r", stdin);
	int numcase = 1;
	while(scanf("%d%d%d", &bdlen, &bdwt, &num) == 3 && (bdlen+bdwt+num))
	{
		for(int i = 0; i < num; ++i)
		{
			scanf("%d%d", &pos[i], &wt[i]);
			pos[i] *= 2;
		}
		memset(rest, -1, sizeof(rest));

		rest[0] = 1;   //a legal final state; nothing left
		
		printf("Case %d:\n", numcase++);
		if(!dfs((1<<num)-1, 3*bdwt, -3*bdwt))
		{
			printf("Impossible\n");
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值