Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

第一道双搜!

Posted by 3088891520 at 2015-07-17 11:19:19 on Problem 1915
#include<cstdio>
#include<iostream>
#include<queue>;
using namespace std;
#define Maxn 309
struct node
{
    int x,y;
};
int n;
int fstep[Maxn][Maxn],bstep[Maxn][Maxn];
int dir[8][2] = {-1,-2,-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2};
bool isok(node a)
{
    if (a.x < 0 || a.x >= n || a.y < 0 || a.y >= n)
        return false;
    return true;
}
int BBFS(node a,node b)
{
    if (a.x == b.x && a.y == b.y)
    {
        return 0;
    }
    int i,j;
    queue<node>q1,q2;
    for (i = 0; i < n; ++i)
    {
        for (j = 0; j < n; ++j)
            fstep[i][j] = bstep[i][j] = -1;
    }
    fstep[a.x][a.y] = 0;
    bstep[b.x][b.y] = 0;
    q1.push(a);
    q2.push(b);
    while (!q1.empty() && !q2.empty())
    {
        node tt,t1,t2;
        if (!q1.empty())
        {
            t1 = q1.front();
            q1.pop();
            for (i = 0; i < 8; ++i)
            {
                tt.x = t1.x + dir[i][0];
                tt.y = t1.y + dir[i][1];
                if (isok(tt))
                {
                    if (fstep[tt.x][tt.y] == -1)
                    {
                        fstep[tt.x][tt.y] = fstep[t1.x][t1.y] + 1;
                        q1.push(tt);
                    }
                    if (bstep[tt.x][tt.y] != -1)
                        return fstep[tt.x][tt.y] + bstep[tt.x][tt.y];
                }
            }
        }
        if (!q2.empty())
        {
            t2 = q2.front();
            q2.pop();
            for (i = 0; i < 8; ++i)
            {
                tt.x = t2.x + dir[i][0];
                tt.y = t2.y + dir[i][1];
                if (isok(tt))
                {
                    if (bstep[tt.x][tt.y] == -1)
                    {
                        bstep[tt.x][tt.y] = bstep[t2.x][t2.y] + 1;
                        q2.push(tt);
                    }
                    if (fstep[tt.x][tt.y] != -1)
                        return bstep[tt.x][tt.y] + fstep[tt.x][tt.y];
                }
            }
        }
    }
}
int main()
{
    int t,ans;
    struct node a,b;
    while (~scanf("%d",&t))
    {
        while (t--)
        {
            scanf("%d",&n);
            scanf("%d%d%d%d",&a.x,&a.y,&b.x,&b.y);
            ans = BBFS(a,b);
            printf("%d\n",ans);
        }
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator