A. Two Semiknights Meet
链接:http://codeforces.com/contest/362/problem/A
描述:8*8的棋盘上有两个semiknight,并且它只能走"日“字。即int dir[][2] = {{-2,-2}, {-2,2}, {2,2}, {2,-2}};
现在两个semiknight 同时 移动(一开始没看见"同时"坑了)。判断能否在允许相遇的格子相遇。
思路:照理说第一题没那么麻烦的,但是一开始没想到好方法,只能用搜索。首先分别用广搜记录K到每个能到达格点的最短时间,然后只需要判断这个时间是不是同奇偶性就行了,因为可以往回走,所以只要满足奇偶性相同就可以相遇。
后来看到另一个数学方法:直接判断两个K的横纵坐标之差都能被4整除就可以了。
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int dir[][2] = {{-2,-2}, {-2,2}, {2,2}, {2,-2}};
char map1[9][9], map2[9][9];
bool vis1[9][9], vis2[9][9];
int step1[9][9], step2[9][9];
struct T {
int x, y, step;
T(int x = 0, int y = 0, int step = 0) : x(x), y(y), step(step) { }
};
void bfs(int x, int y, char map[][9], bool vis[][9], int ste[][9])
{
vis[x][y] = 1;
ste[x][y] = 0;
queue<T> q;
q.push(T(x,y,0));
while (!q.empty()) {
T now = q.front(); q.pop();
for (int i = 0; i < 4; ++i) {
T next(now.x+dir[i][0], now.y+dir[i][1], now.step+1);
if (next.x>=1 && next.x<=8 && next.y>=1 && next.y<=8 && !vis[next.x][next.y]) {
vis[next.x][next.y] = 1;
ste[next.x][next.y] = now.step + 1;
q.push(next);
}
}
}
}
inline bool is_same_parity(int a, int b) //奇偶性判断
{ return ((a & 1) == (b & 1)); }
int main()
{
int t;
while (scanf("%d", &t) != EOF) {
while (t--) {
vector<int> p;
for (int i = 1; i <= 8; ++i)
for (int j = 1; j <= 8; ++j) {
cin >> map1[i][j];
if (map1[i][j] == 'K')
p.push_back(i), p.push_back(j);
map2[i][j] = map1[i][j];
}
memset(vis1, 0, sizeof(vis1)); memset(vis2, 0, sizeof(vis2));
memset(step1, 0, sizeof(step1)); memset(step2, 0, sizeof(step2));
bfs(p[0], p[1], map1, vis1, step1);
bfs(p[2], p[3], map2, vis2, step2);
bool flag = 0;
for (int i = 1; i <= 8; ++i)
for (int j = 1; j <= 8; ++j)
if (is_same_parity(step1[i][j], step2[i][j]) && vis1[i][j] && vis2[i][j]
&& map1[i][j] != '#') {
flag = 1;
break;
}
if (flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
数学方法:
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main()
{
int t;
while (cin >> t) {
while (t--) {
char c;
vector<int> p;
for (int i = 1; i <= 8; ++i)
for (int j = 1; j <= 8; ++j) {
cin >> c;
if (c == 'K')
p.push_back(i), p.push_back(j);
}
if ((p[2]-p[0])%4 == 0 && (p[3]-p[1])%4 == 0) //(p[0],p[1]) (p[2],p[3])是两个K的坐标
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}