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;
}


發佈了105 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章