bzoj 1193 貪心+bfs

1193: [HNOI2006]馬步距離

Time Limit: 10 Sec  Memory Limit: 162 MB
Submit: 2015  Solved: 914
[Submit][Status][Discuss]

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。php

Output

含一個整數,表示從點p到點s至少須要通過的馬步移動次數。ios

Sample Input

1 2 7 9

Sample Output

5

HINT

//大範圍貪心,小範圍bfs便可,貪心時橫縱距離誰大誰減2,還要橫縱距離控制在不小於起點。之前作過一個大範圍貪心小範圍dp。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int MAXN=100009;
bool vis[300][300];
int dir[8][2]={2,1,2,-1,1,2,1,-2,-2,1,-2,-1,-1,2,-1,-2};
int dfs(int sx,int sy,int ex,int ey)
{
    queue<int>q;
    vis[sx][sy]=1;
    q.push(sx);q.push(sy);q.push(0);
    while(!q.empty()){
        int x=q.front();q.pop();
        int y=q.front();q.pop();
        int cnt=q.front();q.pop();
        if(x==ex&&y==ey) return cnt;
        for(int i=0;i<8;i++){
            int xx=x+dir[i][0],yy=y+dir[i][1];
            if(xx<90||xx>210||yy<90||yy>210) continue;
            if(vis[xx][yy]) continue;
            vis[xx][yy]=1;
            q.push(xx);q.push(yy);q.push(cnt+1);
        }
    }
}
int main()
{
    int sx,sy,ex,ey;
    memset(vis,0,sizeof(vis));
    scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
    ex-=sx;ey-=sy;
    sx=sy=100;
    if(ex<0) ex=-ex;
    if(ey<0) ey=-ey;
    ex+=100;ey+=100;
    ll ans=0;
    while(ex-sx>=100||ey-sy>=100){
        if(ex>=ey){
            ex-=2;
            if(ey>100) ey-=1;
            else ey+=1;
        }else{
            ey-=2;
            if(ex>100) ex-=1;
            else ex+=1;
        }
        ans++;
    }
    ans+=dfs(sx,sy,ex,ey);
    printf("%lld\n",ans);
    return 0;
}
相關文章
相關標籤/搜索