参考了 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");
}
}
}