BZOJ1193 [HNOI2006]马步距离(洛谷P2060)

BFS 贪心

BZOJ题目传送门
洛谷题目传送门

先贪心地尽量接近,然后BFS。

代码(有哪位dalao能看看为什么我答案+1才对):

#include<cstdio>
#include<cstring>
#include<algorithm>
#define abs(x) ((x)>0?(x):-(x))
using namespace std;
const int t1[8]={1,1,-1,-1,2,2,-2,-2};
const int t2[8]={2,-2,2,-2,1,-1,1,-1};
int xp,yp,xs,ys,q[100005][2],d[205][205];
inline int hhh(){
    int ans=0;
    for(;xs+ys>50;ans+=2){
        if (xs<ys) swap(xs,ys);
        xs-=4,ys-=2*(xs-4<ys*2);
    }
    return ans;
}
inline int bfs(){
    memset(d,-1,sizeof(d));
    int l=0,r=1; xs+=70,ys+=70;
    q[1][0]=q[1][1]=70,d[50][50]=0;
    while (l<=r){
        int s=q[++l][0],t=q[l][1];
        if (s==xs&&t==ys) return d[s][t];
        for (int i=0;i<8;i++){
            int x=s+t1[i],y=t+t2[i];
            if (x>=0&&x<205&&y>=0&&y<205&&d[x][y]==-1)
                d[x][y]=d[s][t]+1,q[++r][0]=x,q[r][1]=y;
        }
    }
}
int main(){
    scanf("%d%d%d%d",&xp,&yp,&xs,&ys);
    xs=abs(xs-xp),ys=abs(ys-yp);
    return printf("%d\n",hhh()+bfs()+1),0;
}

猜你喜欢

转载自blog.csdn.net/a1799342217/article/details/80945552
今日推荐