您的位置:首页 > 运维架构

[Topcoder] SRM207

2010-07-19 20:21 405 查看
Div2 Lev3

 

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <deque>
using namespace std;

typedef struct node {
string pos;
int hasKillRook;
int hasKillQueen;
int step;
} node;

const int coffset[8] = {-2, -2, 2, 2, -1, 1, -1, 1};
const int roffset[8] = {-1, 1, -1, 1, -2, -2, 2, 2};

class CaptureThemAll {
private:

public:
int fastKnight(string knight, string rook, string queen) {
int visited[4][64] = {0};
deque<node> q;
// push the first pos of knight
node n;
n.pos = knight;
n.hasKillRook = 0;
n.hasKillQueen = 0;
n.step = 0;
visited[0][64] = 1;
q.push_back(n);

while (!q.empty()) {
n = q.front();
q.pop_front();
cerr << n.pos << endl;

if (n.hasKillQueen && n.hasKillRook)
return n.step;
else if (n.hasKillQueen)
visited[2][(n.pos[0] - 'a') * 8 + n.pos[1] - '1']++;
else if (n.hasKillRook)
visited[1][(n.pos[0] - 'a') * 8 + n.pos[1] - '1']++;
else
visited[0][(n.pos[0] - 'a') * 8 + n.pos[1] - '1']++;

for (int i = 0; i < 8; i++) {
string curp(2, '/0');
curp[0] = n.pos[0] + coffset[i];
curp[1] = n.pos[1] + roffset[i];

// out of bound
if (curp[0] < 'a' || curp[0] > 'h' ||
curp[1] < '1' || curp[1] > '8')
continue;

node newn = n;
newn.pos = curp;
if (curp == queen)
newn.hasKillQueen = 1;
if (curp == rook)
newn.hasKillRook = 1;
newn.step++;

int flg = 0;
if (newn.hasKillQueen && newn.hasKillRook)
return newn.step;
else if (newn.hasKillQueen)
flg = 2;
else if (newn.hasKillRook)
flg = 1;
else
flg = 0;

if (visited[flg][(newn.pos[0] - 'a') * 8 + newn.pos[1] - '1'])
continue;

q.push_back(newn);
}
}

return -1;
}
};

int main()
{
CaptureThemAll cta;
cout << "example 0: " << cta.fastKnight("a1", "b3", "c5") << endl;
cout << "example 1: " << cta.fastKnight("b1", "c3", "a3") << endl;
cout << "example 2: " << cta.fastKnight("a1", "a2", "b2") << endl;
cout << "example 3: " << cta.fastKnight("a5", "b7", "e4") << endl;
cout << "example 4: " << cta.fastKnight("h8", "e2", "d2") << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: