【HDOJ】1401 Solitaire

双向BFS+状态压缩。

 /* 1401 */
#include <iostream>
#include <queue>
#include <map>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std; struct Point_t{
char x, y;
friend bool operator ==(const Point_t &a, const Point_t &b) {
return a.x==b.x && a.y==b.y;
}
}; typedef struct Node_t {
Point_t p[];
int t;
} Node_t; const char n = ;
Node_t b1, b2;
map<int, int> tb;
char dir[][] = {
-,,,,,-,,
}; bool comp(const Point_t &a, const Point_t &b) {
if (a.x == b.x)
return a.y < b.y;
return a.x < b.x;
} int calHash(Node_t nd) {
int ret = ;
int i, j; for (i=,j=; i<; ++i,j+=) {
ret |= (nd.p[i].x << j);
ret |= (nd.p[i].y << (j+));
}
return ret;
} bool judge(Node_t &nd, int v, int d) {
int i, j, k; nd.p[v].x += dir[d][];
nd.p[v].y += dir[d][]; if (nd.p[v].x<= || nd.p[v].x>n || nd.p[v].y<= || nd.p[v].y>n)
return false; for (i=; i<; ++i) {
if (i != v) {
if (nd.p[i] == nd.p[v]) {
// jump over one piece
nd.p[v].x += dir[d][];
nd.p[v].y += dir[d][];
if (nd.p[v].x<= || nd.p[v].x>n || nd.p[v].y<= || nd.p[v].y>n)
return false;
for (j=; j<; ++j)
if (j!=v && nd.p[j]==nd.p[v])
return false;
break;
}
}
} sort(nd.p, nd.p+, comp);
return true;
} int bfs() {
int i, j, k;
queue<Node_t> Q1, Q2;
Node_t nd, tmp; sort(b1.p, b1.p+, comp);
sort(b2.p, b2.p+, comp);
Q1.push(b1);
Q2.push(b2);
tb[calHash(b1)] = ;
tb[calHash(b2)] = ; while (!Q1.empty() || !Q2.empty()) {
if (!Q1.empty()) {
nd = Q1.front();
Q1.pop();
if (nd.t < ) {
tmp = nd;
++tmp.t;
for (i=; i<; ++i) {
for (j=; j<; ++j) {
nd = tmp;
if (judge(nd, i, j)) {
k = calHash(nd);
if (tb[k] == )
return ;
if (tb[k] != ) {
Q1.push(nd);
tb[k] = ;
}
}
}
}
}
}
if (!Q2.empty()) {
nd = Q2.front();
Q2.pop();
if (nd.t < ) {
tmp = nd;
++tmp.t;
for (i=; i<; ++i) {
for (j=; j<; ++j) {
nd = tmp;
if (judge(nd, i, j)) {
k = calHash(nd);
if (tb[k] == )
return ;
if (tb[k] != ) {
Q2.push(nd);
tb[k] = ;
}
}
}
}
}
}
} return ;
} int main() {
int i, j, k; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif b1.t = b2.t = ;
while (scanf("%d %d", &b1.p[].x, &b1.p[].y) != EOF) {
for (i=; i<; ++i)
scanf("%d %d", &b1.p[i].x, &b1.p[i].y);
for (i=; i<; ++i)
scanf("%d %d", &b2.p[i].x, &b2.p[i].y);
tb.clear();
k = bfs();
if (k)
puts("YES");
else
puts("NO");
} return ;
}
上一篇:经典ajax 状态响应图


下一篇:写Action的三种方法