[SCOI2005] chivalry

\ (IDA ^ * \) study notes

Specific pre-posture

In fact, I also sell off now, is that I IQ is too low, a lot of reference information in order to understand IDA *, want to help others like me chicken dish (though I may be so much food) and review their future use, the abstract of IDA * and combine this specific problem, thinking it may be better to understand a little qwq

We \ (g (n) \) indicates the actual number of steps node, is already found a few steps.

\ (h (n) \) represents the "Goo price function" node, by definition, goo count probably even found a few steps (from the current node to the end), and ensure that the actual cost of not more than \ (h (n) \) smaller. This is reflected in the title of the current state and the final state how many inconsistent. (By the way, this is the tree sectional sister told nest, this acknowledgment qwq

Then make

\[f(n)=g(n)+h(n)\]

So this optimization problem came out, \ (f (the n-) \) apparently \ (≤15 \) , and then search Jiuhaola!

(In fact, do not look at the code of qwq, understand the idea of ​​direct search Jiuhaola ~

Code


#include<iostream>
#include<cstdio>

using namespace std;

const int inf = 1e9;
int T,ans;
char map[5][5],fin[5][5]=
{
    {'1','1','1','1','1'},
    {'0','1','1','1','1'},
    {'0','0','*','1','1'},
    {'0','0','0','0','1'},
    {'0','0','0','0','0'}
};

int sx,sy;
int dx[8]={1,1,-1,-1,2,2,-2,-2};
int dy[8]={2,-2,2,-2,1,-1,1,-1};

int f()
{
    int cnt=0;
    for(int i=0;i<5;++i)
        for(int j=0;j<5;++j)
            if(map[i][j]!=fin[i][j])
                ++cnt;
    return cnt;
}

void init()
{
    string s[5];
    for(int i=0;i<5;++i) cin>>s[i];
    for(int i=0;i<5;++i)
    {
        for(int j=0;j<5;++j)
        {
            map[i][j]=s[i][j];
            if(map[i][j]=='*') {sx=j;sy=i;}
        }
    }
}

void dfs(int x,int y,int fx,int fy,int g)
// (x,y) means the node where I am now, and g means the distance I have gone 
{
    int h=f();//F=g+h (not f()!!! 
    if(h+g>16) return;//Bao Xian QwQ 
    if(g>=ans) return;
    if(h==0) {ans=g;return;}
    for(int i=0;i<8;++i)
    {
        int nx=x+dx[i],ny=y+dy[i];
        if(nx<0||ny<0||nx>4||ny>4) continue;
        if(nx==fx&&ny==fy) continue;//can't go back 
        swap(map[nx][ny],map[x][y]);
        dfs(nx,ny,x,y,g+1);
        swap(map[nx][ny],map[x][y]);
    }
}

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        init();
        ans=inf;
        dfs(sy,sx,0,0,0);
        if(ans==inf) printf("-1\n");
        else printf("%d\n",ans);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/oierwyh/p/11825286.html