题目链接
http://poj.org/problem?id=2331
题意:
给出n种管子不同长度的管子,每种管子都有一定的数量且只能横着或竖着放,问最少使用多少个管子可以使得管子从起点连接到终点。
题解:
IDA*算法的第一题,它的优化在于预先处理出一个估价函数h[ i ],表示不考虑任何限制的情况下(在本题中即 使用任意数量的管子),i位置到达终点所要耗费的最少管子数,此时每当我们搜到一定程度时,用当前搜到的数量,如果加上这个估算值h[x],已经大于规定的最优值时,说明此时搜到的这个状态肯定无解,这样的话,整个dfs就是一个判断,因此需要枚举所有可行的ans,从小到大枚举,当ans取某一值使得dfs判断合法时,说明此时的ans就是答案。
在本题中,因为管子无法弯折,只能横着或竖着,所以将水平方向与竖直方向分别判断是否合法是比较方便的做法。
代码:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
queue<int>q;
int n,ans,stx,sty,edx,edy,h1[2050],h2[2050],tot;
int len[15],sum[15];
void cal(int *h,int pos)//预处理估算值
{
while(!q.empty())q.pop();
q.push(pos);
h[pos]=0;
while(!q.empty())
{
int now=q.front();q.pop();
for (int i=1;i<=n;i++)
{
int nex=now+len[i];
if ( nex<=1000 && h[nex]==-1)
{
h[nex]=h[pos]+1;
q.push(nex);
}
nex=nex-2*len[i];
if ( nex>0 && h[nex]==-1)
{
h[nex]=h[pos]+1;
q.push(nex);
}
}
}
}
int dfs(int *a,int x,int dep,int p)//dfs搜索
{
int now;
if (p==1) now=h1[x];
else now=h2[x];
//当这个位置即使在不限条件下,也达不到终点,或,加上当前的数量已经超出规定的最优值,那么返回0表示不能搜到
if (now==-1 || now+dep>ans) return 0;
if (now==0)
{
if (p==1)//用p来现在是横的还是竖的
return dfs(a,sty,dep,0);
else return 1;
}
int tmps[15];
for (int i=1;i<=n;i++) tmps[i]=a[i];
for (int i=1;i<=n;i++)
if (tmps[i]>0)
{
tmps[i]--;
int nex=x+len[i];
if (nex<=1000 && dfs(tmps,nex,dep+1,p))
return 1;
nex=nex-2*len[i];
if (nex>0 && dfs(tmps,nex,dep+1,p))
return 1;
tmps[i]++;
}
return 0;
}
int main()
{
tot=0;
scanf("%d%d%d%d",&stx,&sty,&edx,&edy);
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%d",&len[i]);
for (int i=1;i<=n;i++)
{
scanf("%d",&sum[i]);
tot+=sum[i];
}
memset(h1,-1,sizeof(h1));
memset(h2,-1,sizeof(h2));
cal(h1,edx);
cal(h2,edy);
if (stx==edx&&sty==edy)
{
printf("0\n");
return 0;
}
for (int i=1;i<=tot+1;i++)//枚举所有ans,发现答案后立刻break
{
ans=i;
if (dfs(sum,stx,0,1)) break;
}
if (ans==tot+1)//如果1~tot之内的数量都无法满足条件,因为最多只有tot个管子,所以输出-1
printf("-1\n");
else
printf("%d\n",ans);
}