P2324 [SCOI2005] chivalry (A *)

P2324 [SCOI2005] chivalry

A * search and the critical difference is that it has a cost function $ h (x) $

This evaluation function is usually set to the minimum number of steps from the current state to the end state estimation, which can effectively prune

However, the estimated value must be strictly less than equal to the actual remaining number of steps, otherwise it will affect the accuracy of excessive pruning

$ G (x), f (x) $ are the remaining number of steps and walking is the number, then:

$g(x)=f(x)+h(x)$

The title of the $ h (x) $ can be set to the number of pieces is not homing +1

Because each step up to make a piece homing (except the last step at a time homing 2 pieces)

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int d1[8]={1,1,2,2,-1,-1,-2,-2};
int d2[8]={2,-2,1,-1,2,-2,1,-1};
char a[9][9]; int Re, COL [ . 9 ] [ . 9 ]; 
inline BOOL  IS ( int X, int Y) { return (X == . 3 && Y == . 3 ?) (A [X] [Y] == ' * ' ) :( A [X] [Y] == COL [X] [Y] + ' 0 ' );}
 void DFS ( int D, int S, int X, int Y) { // D current step number, s is homing The number of pieces 
    IF (D + 24 -s> || Re = D> 15 ) return ; // F (X) = D, G (X) = S-24
    if(s==25) {re=min(re,d); return ;}
    for(int i=0;i<8;++i){
        int rx=x+d1[i],ry=y+d2[i],p=s;
        if(rx<1||5<rx||ry<1||5<ry) continue;
        p-=is(x,y)+is(rx,ry);
        swap(a[x][y],a[rx][ry]);
        p+=is(x,y)+is(rx,ry);
        dfs(d+1,p,rx,ry);
        swap(a[x][y],a[rx][ry]);
    }
}
int main(){
    for(int i=1;i<=5;++i) for(int j=i;j<=5;++j) col[i][j]=1;
    col[4][4]=col[5][5]=0;
    int T,sum,fx,fy;scanf("%d",&T);
    while(T--){
        sum=0; re=16;
        for(int i=1;i<=5;++i){
            scanf("%s",a[i]+1);
            for(int j=1;j<=5;++j){
                sum+=is(i,j);
                if(a[i][j]=='*') fx=i,fy=j;
            }
        }dfs(0,sum,fx,fy);
        if(re>15) re=-1;
        printf("%d\n",re);
    }return 0;
} 

 

Guess you like

Origin www.cnblogs.com/kafuuchino/p/11285586.html