hihoCoder 1308:搜索二·骑士问题(BFS预处理)

题目链接

题意

中文题意。

思路

对于每一个骑士,可以先预处理出到达地图上某个点的需要走的步数,然后最后暴力枚举地图上每一个点,让三个骑士走过的距离之和最小即可。

#include <bits/stdc++.h>
using namespace std;
const int INF = 300;
const int N = 1e5 + 10;
#define fir first
#define sec second
typedef long long LL;
typedef pair<int, int> pii;
char s[5];
int dx[] = {2, 2, -2, -2, 1, 1, -1, -1}, dy[] = {1, -1, 1, -1, 2, -2, 2, -2};
int xx[3], yy[3], ans, dis[3][9][9];

void BFS(int x, int y, int dis[9][9]) {
    for(int i = 0; i < 8; i++)
        for(int j = 0; j < 8; j++) dis[i][j] = INF;
    queue<pii> que;
    que.push({x, y}); dis[x][y] = 0;
    while(!que.empty()) {
        pii now = que.front(); que.pop();
        x = now.fir, y = now.sec;
        for(int i = 0; i < 8; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if(nx < 0 || nx >= 8 || ny < 0 || ny >= 8) continue;
            if(dis[nx][ny] == INF)
                dis[nx][ny] = dis[x][y] + 1, que.push({nx, ny});
        }
    }
}

int main() {
    int t; scanf("%d", &t);
    while(t--) {
        for(int i = 0; i < 3; i++) {
            scanf(" %s", s);
            int x = s[0] - 'A', y = s[1] - '1';
            BFS(x, y, dis[i]);
        }
        int ans = INF;
        for(int i = 0; i < 8; i++)
            for(int j = 0; j < 8; j++)
                if(dis[0][i][j] + dis[1][i][j] + dis[2][i][j] < ans)
                    ans = dis[0][i][j] + dis[1][i][j] + dis[2][i][j];
        printf("%d
", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/fightfordream/p/7586168.html