poj2286(IDA*)

解题思路:以前知道IDA*比较简单,所以没怎么练,今天练一次试试。IDA*其实就是加上估计函数的迭代加深搜索(不断增加深度,与A*相比节约内存,但会重复搜索)。加不加估计函数真的是效果完全不一样。不加就超时(我见过一些玄学估计函数,但我这次选的估计函数不是玄学)。

代码摘自https://www.cnblogs.com/nwpuacmteams/articles/5658403.html

写得已经很简单明了了

#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stdlib.h>
using namespace std;
int a[25];
int p[8] = {6,7,8,11,12,15,16,17};//中间8个所对应的序号
int rev[8] = {5,4,7,6,1,0,3,2};//A-F B-E...反着移动
int v,ans[110];
int po[8][7] = {0,2,6,11,15,20,22,
            1,3,8,12,17,21,23,
            10,9,8,7,6,5,4,
            19,18,17,16,15,14,13,
            23,21,17,12,8,3,1,
            22,20,15,11,6,2,0,
            13,14,15,16,17,18,19,
            4,5,6,7,8,9,10};//8种操作的原始顺序 对应ABCDEFGH
void change(int k)//操作一次的结果
{
    int i,y = a[po[k][0]];
    for(i = 0 ; i < 6 ; i++)
    a[po[k][i]] = a[po[k][i+1]];
    a[po[k][6]] = y;
}
int fdep()//这个是简单的估计下还需要搜得层数 假如中间已经有5个相同的了 那最少还要移3次
{
    int i,x[4] = {0,0,0,0};
    for(i = 0 ; i < 8 ; i++)
    x[a[p[i]]]++;
    int an=0;
    for(i = 1 ; i < 4 ; i++)
    an = max(an,x[i]);
    return 8-an;
}
int dfs(int depth)
{
    int i,tt;
    for(i = 0 ; i < 8 ; i++)
    {
        change(i);//操作
        tt = fdep();
        if(tt==0)//已经到达目的解
        {
            ans[depth] = i;
            return 1;
        }
        if(depth+tt<v)//如果没有超过层数限制
        {
            ans[depth] = i;
            if(dfs(depth+1))
            return 1;
        }
        change(rev[i]);//撤销操作
    }
    return 0;
}
int main()
{
    int i;
    while(scanf("%d",&a[0])&&a[0])
    {
        for(i = 1 ; i < 24 ; i++)
        scanf("%d",&a[i]);
        if(fdep()==0)
        {
            puts("No moves needed");
            printf("%d\n",a[17]);//这里不要忘了输出
            continue;
        }
        v = 1;
        while(!dfs(0))
        {
            v++;
        }
        for(i = 0 ; i < v ; i++)
        printf("%c",ans[i]+'A');
        puts("");
        printf("%d\n",a[15]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39861441/article/details/87908279
今日推荐