题目链接
题目大意:
考虑一个象棋残局,其中红方有n(2<=n<=7)个棋子,黑方只有一个将。红方除了有一个帅(G)之外还有3种可能的
棋子:车(R),马(H),炮(C),并且需要考虑“蹩马脚”,将与帅不能照面(将,帅如果在同一直线上,中 间无其它棋子阻挡时,走子的一方胜)的规则。
输入所有棋子的位置,保证局面合法并且红方已经将军。你的任务是判断红方是否已经把黑方将死。 ————翻译取自《算法竞赛入门经典》
分析:
细节模拟题,一直放着没做,今天一做发现不简单,看的一位博主的思路。有几点坑:
1:因为是该黑棋走的环节,黑棋会吃掉红棋子。
2:黑棋红棋子直接照面,为no,因为红棋子输了。
思路便是:黑棋子有四种走法(上下左右),每一步都判断当前情况下会不会被吃掉。
因为车,炮需要考虑两棋子间的棋子个数,所以写了一个单独的函数来判断。然后每一步都遍历一遍红棋子,看是否有棋子可是吃掉当前情况下的黑帅。
思路很重要!!!!!!
#include <bits/stdc++.h>
using namespace std;
//黑将的走位
int dir[5][5] = {{-1,0},{1,0},{0,-1},{0,1}};
//马的走位
int horse[10][5] = {{-2,-1},{-2,1},{2,1},{2,-1},{1,-2},{-1,-2},{1,2},{-1,2}};
multimap<char,pair<int,int>> chess;
int board[15][15],black_r, black_c;
//0 行 =x 1 列 =y
int count(int a1, int a2, int b, int judge) { //判断两棋子之间是否有棋子
if(a1>a2) swap(a1,a2);
int cnt = 0;
if(!judge) {
for(int i = a1+1; i < a2; i++) {
if(board[b][i]) cnt++;
}
}
else {
for(int i = a1+1; i < a2; i++) {
if(board[i][b]) cnt++;
}
}
return cnt;
}
bool Judge(int br, int bc) {
bool flag = false;
for (auto &ches : chess) {
int redr = ches.second.first, redc = ches.second.second;
char cs = ches.first;
if(br==redr && bc==redc) continue;//黑棋吃了红棋子
if(cs=='G') {
if(black_c==redc && !count(black_r,redr,redc,1))
return false;
if(bc==redc && !count(br,redr,bc,1))
flag = true;
}
else if(cs=='R') {
if(bc==redc && count(br,redr,bc,1)==0)
flag = true;
else if(br==redr && count(bc,redc,br,0)==0)
flag = true;
}
else if(cs=='C') {
if(bc==redc && count(br,redr,bc,1)==1)
flag = true;
else if(br==redr && count(bc,redc,br,0)==1)
flag = true;
}
else if(cs=='H') {
for(int i = 0; i < 8; i++) {
int nexthr = redr+horse[i][0];
int nexthc = redc+horse[i][1];
//不蹩脚
if(!board[redr+dir[i/2][0]][redc+dir[i/2][1]]) {
if(br==nexthr && bc==nexthc)
flag = true;
}
}
}
}
return flag;
}
int main() {
int n;
while(cin >> n >> black_r >> black_c &&n&&black_c&&black_c) {
memset(board,0,sizeof(board));
chess.clear();
while(n--) {
char ch; int rr,cc;
cin >> ch >> rr >> cc;
chess.insert({ch,make_pair(rr,cc)});
board[rr][cc] = 1;
}
bool result = true;
for(int i = 0; i < 4; i++) {
int nextr = black_r+dir[i][0];
int nextc = black_c+dir[i][1];
if(nextr>=1 && nextr<=3 && nextc>=4 && nextc<=6) {
if(!Judge(nextr,nextc))//有一个为false,则不成功
result = false;
}
}
if(result) cout << "YES" << endl;
else cout << "NO" << endl;
}
}