POJ2331Water pipe(IDA*)

31 篇文章 0 订阅
9 篇文章 0 订阅

本来用哈弗曼距离作为h函数,T了。看了大神的博客才知道要先对x轴,y轴预处理h函数。也就是对于终点的ed.x,要在0< x< = 1000的范围中将h(x)先算出来(h(ed.x)=0),h[tp+L[i]]=h[tp]+1;h[tp-L[i]]=h[tp]+1。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <stack>
#include <vector>
#include <string.h>
#include <queue>
#define msc(X) memset(X,-1,sizeof(X))
#define ms(X) memset(X,0,sizeof(X))
#define mabs(X) ((X)>0?(X):(-(X)))
typedef long long LL;
using namespace std;
int L[6],C[6],k,mln=0;
struct _Point
{
    int x,y;
    int C[6];
}st,ed;
void cal_h(int *h,int t)
{
    queue<int > q;
    while(!q.empty()) q.pop();
    h[t]=0;
    q.push(t);
    while(!q.empty()){
        int tp=q.front();
        q.pop();
        for(int i=0;i<k;i++)
        {       
            if(tp+L[i]<=1000&&h[tp+L[i]]==-1){
                h[tp+L[i]]=h[tp]+1;
                q.push(tp+L[i]);
            }
            if(tp-L[i]>0&&h[tp-L[i]]==-1){
                h[tp-L[i]]=h[tp]+1;
                q.push(tp-L[i]);
            }
        }
    }
}
int pLt,hx[1020],hy[1020];
bool IDA(struct _Point cur,int d,int type)
{
    int hv=type?hy[cur.y]:hx[cur.x];
    if(hv==-1||hv+d>pLt) return false;
    if(hv==0){
        if(type) {printf("%d\n",pLt );
            return true;}
        else return IDA(cur,d,1);
    }
    struct _Point next;
    for(int j=0;j<k;j++)
    {
        if(cur.C[j]>=C[j]) continue;
        if(!type){
            next=cur;
            next.C[j]++;
            next.x+=L[j];
            if(next.x<=1000&&IDA(next,d+1,type))
                return true;
            next=cur;
            next.C[j]++;
            next.x-=L[j];
            if(next.x>0&&IDA(next,d+1,type))
                return true;
        }
        else{
            next=cur;
            next.C[j]++;
            next.y+=L[j];
            if(next.y<=1000&&IDA(next,d+1,type))
                return true;
            next=cur;
            next.C[j]++;
            next.y-=L[j];
            if(next.y>0&&IDA(next,d+1,type))
                return true;
        }
    }
    return false;
}
int main(int argc, char const *argv[])
{
    int mx=0;
    scanf("%d %d %d %d",&st.x,&st.y,&ed.x,&ed.y);
    scanf("%d",&k);
    for(int i=0;i<k;i++) {scanf("%d",L+i);mln=max(mln,L[i]);}
    for(int i=0;i<k;i++) {scanf("%d",C+i);mx+=C[i];}
    for(int i=0;i<k;i++)
        st.C[i]=ed.C[i]=0;
    msc(hx);
    msc(hy);
    cal_h(hx,ed.x);
    cal_h(hy,ed.y);
    if(hx[st.x]==-1||hy[st.y]==-1) {puts("-1");return 0;}
    for(pLt=hx[st.x]+hy[st.y];pLt<=mx;pLt++)
        if(IDA(st,0,0)) break;
    if(pLt>mx) puts("-1");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值