题解:UVA11405 Can U Win?
国际象棋策略问题(翻译)
你正在和妹妹下国际象棋。可惜她太聪明了,你根本不是对手 —— 眼下你只剩一个国王和一个骑士,眼看就要输了。妹妹超爱吃 “panju muttai”(也就是我们常说的棉花糖)。刚好卖 “panju muttai” 的小贩来了,妹妹就出去买棉花糖了。 你是个老实人,也一直要求自己诚实守信,但同时你也挺机灵的。你这样安慰自己:妹妹这是在 “过招”(没错,这个版本的国际象棋允许 “过招”,即不移动棋子跳过回合),那我走的棋就算是 “合法” 的! 你发现了一个关键情况:不知为何,妹妹只有在所有兵都被吃掉的情况下,才会输掉这盘棋。你还意识到,妹妹不在的时候,你不能吃掉除兵以外的其他棋子。那么问题来了:在妹妹回来之前,你最多走 n 步(这些棋是合法的还是不合法的呢?),能确保自己赢吗? 棋子表示说明 你的国王 = 'K' 你的骑士 = 'k' 对方的兵 = 'P' 对方的其他棋子 = 'p' 空位 = '.' 规则限制 只有妹妹在场时,你才能移动你的国王。 骑士必须走合法的国际象棋步法(即 “L 形” 步法:横向走 2 格再纵向走 1 格,或横向走 1 格再纵向走 2 格)。 棋盘上必然有 1 个 'K'、1 个 'k',0 到 8 个 'P',0 到 8 个 'p'。 输入格式 第一行输入一个整数 t,表示测试用例的数量,其中 1 < t ≤ 100。 每个测试用例的输入格式如下: 第一行输入一个整数 n,表示妹妹回来前你最多能走的步数。 接下来 8 行,每行输入 8 个字符,描述棋盘的布局。 每个测试用例前会有一个空行。 输出格式 对于每个测试用例,在单独一行中输出结果: 如果能在不超过 n 步的情况下确保获胜,输出 “Yes”。 如果无法做到,输出 “No”。
#include <iostream>
#include <vector>
#include <climits>
#include <sstream>
#include <algorithm>
using namespace std;
// 骑士的8种可能移动方向(L形移动)
const int dx[] = {2, 1, -1, -2, -2, -1, 1, 2};
const int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};
// 计算从起点到每个目标点的最短步数
vector<int> compute_distances(int start_x, int start_y, const vector<pair<int, int>>& targets) {
vector<int> distances;
for (const auto& target : targets) {
int tx = target.first;
int ty = target.second;
// 初始化距离矩阵,-1表示未访问
vector<vector<int>> dist(8, vector<int>(8, -1));
vector<pair<int, int>> queue;
// 起点入队
dist[start_x][start_y] = 0;
queue.emplace_back(start_x, start_y);
int q_idx = 0;
// BFS计算最短路径
while (q_idx < queue.size()) {
auto [x, y] = queue[q_idx++];
// 到达目标点,记录距离并退出
if (x == tx && y == ty) {
distances.push_back(dist[x][y]);
break;
}
// 尝试所有可能的移动
for (int i = 0; i < 8; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
// 检查是否在棋盘范围内且未访问
if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && dist[nx][ny] == -1) {
dist[nx][ny] = dist[x][y] + 1;
queue.emplace_back(nx, ny);
}
}
}
}
return distances;
}
int main() {
int t;
string line;
// 读取测试用例数量
getline(cin, line);
t = stoi(line);
while (t--) {
// 跳过测试用例前的空行
while (true) {
if (!getline(cin, line)) break;
if (line.empty()) continue;
else break;
}
// 读取最大允许步数n
int n = stoi(line);
// 读取棋盘
vector<string> board(8);
for (int i = 0; i < 8; ++i) {
getline(cin, board[i]);
}
// 寻找骑士位置和所有对方兵的位置
int kx = -1, ky = -1;
vector<pair<int, int>> pawns;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (board[i][j] == 'k') {
kx = i;
ky = j;
} else if (board[i][j] == 'P') {
pawns.emplace_back(i, j);
}
}
}
// 没有兵需要吃,直接获胜
if (pawns.empty()) {
cout << "Yes" << endl;
continue;
}
// 计算骑士到每个兵的最短距离
vector<int> distances = compute_distances(kx, ky, pawns);
// 计算总步数(所有最短距离之和)
int total = 0;
for (int d : distances) {
total += d;
}
// 判断总步数是否在允许范围内
if (total <= n) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}