BZOJ1193: [HNOI2006]马步距离

易水人去,明月如霜。

Description

在国际象棋和中国象棋中,马的移动规则相同,都是走“日”字,我们将这种移动方式称为马步移动。如图所示,
从标号为 0 的点出发,可以经过一步马步移动达到标号为 1 的点,经过两步马步移动达到标号为 2 的点。任给
平面上的两点 p 和 s ,它们的坐标分别为 (xp,yp) 和 (xs,ys) ,其中,xp,yp,xs,ys 均为整数。从 (xp,yp) 
出发经过一步马步移动可以达到 (xp+1,yp+2)、(xp+2,yp+1)、(xp+1,yp-2)、(xp+2,yp-1)、(xp-1,yp+2)、(xp-2,
yp+1)、(xp-1,yp-2)、(xp-2,yp-1)。假设棋盘充分大,并且坐标可以为负数。现在请你求出从点 p 到点 s 至少
需要经过多少次马步移动?

Input

只包含4个整数,它们彼此用空格隔开,分别为xp,yp,xs,ys。并且它们的都小于10000000。

Output

含一个整数,表示从点p到点s至少需要经过的马步移动次数。

Sample Input

1 2 7 9

Sample Output

5
思路:大范围贪心,靠近目标点,小范围直接BFS

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int read()
{
    char ch;int s=0,f=1;ch=getchar();
    while(ch>'9'||ch<'0') { if(ch=='-') f*=-1; ch=getchar(); }
    while(ch<='9'&&ch>='0') s=s*10+ch-48,ch=getchar();
    return s*f;
}
struct node {
 int x,y;
};
int x,y;
int xp,yp,xs,ys;
int ans=0;
int dis[105][105];
int xx[8]={1,1,-1,-1,2,2,-2,-2},yy[8]={2,-2,2,-2,1,-1,1,-1};
int qx[10005],qy[10005];

void bfs()
{
    memset(dis,-1,sizeof(dis));
    dis[x][y]=0;
    queue<node> q;
    node s; s.x=x,s.y=y;
    q.push(s);
    while(!q.empty())
    {
        node now=q.front();q.pop();
        for(int i=0;i<8;i++)
        {
            int dx,dy; dx=now.x+xx[i],dy=now.y+yy[i];
            if(dx<0||dy<0||dx>100||dy>100) continue;
            if(dis[dx][dy]!=-1) continue ;
            dis[dx][dy]=dis[now.x][now.y]+1;
            node dd; dd.x=dx,dd.y=dy;
            q.push(dd); if(dx==50&&dy==50) return ;
        }
    }
}

int main()
{
    xp=read(),yp=read(),xs=read(),ys=read();
    x=abs(xp-xs),y=abs(yp-ys);
    while(x+y>=50)
    {
        if(x<y) swap(x,y);
        if(x-4>=2*y) x-=4;
        else x-=4,y-=2;
        ans+=2;
    }
    x+=50,y+=50;

    bfs();
    printf("%d\n",ans+dis[50][50]);
 return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值