标签:uva
题意:
图中15个格子;只有一个是空的,其余都有珠子
你可以把珠子沿图中的一条直线,跳过一个或多个珠子(注意不可以是0个),到达最近的空格,并把中间的珠子拿走;
最后要使只剩一个珠子,并且位置在刚开始的空位那;
思路:
bfs + set判重;
用2进制压缩状态,然后用set<int>判重状态;
一开始打一个表,表示每一个点的6个方向是什么,-1表示没有;因为最后要找字典序最小的,所以方向的顺序应该是左上,右上,左,右,左下,右下,从小到大;
然后就是bfs,每次要跳的时候,就从当前点,选择一个方向,找到有空的位置,或者找到-1了为止;
找到空的,就把空的放上珠子,中间其他位置全部珠子拿走;
AC代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<set> #include<queue> using namespace std; const int N = 15; const int jump[15][6] = {{-1,-1,-1,-1,2,3},{-1,1,-1,3,4,5},{1,-1,2,-1,5,6}, {-1,2,-1,5,7,8},{2,3,4,6,8,9},{3,-1,5,-1,9,10}, {-1,4,-1,8,11,12},{4,5,7,9,12,13},{5,6,8,10,13,14}, {6,-1,9,-1,14,15},{-1,7,-1,12,-1,-1},{7,8,11,13,-1,-1}, {8,9,12,14,-1,-1},{9,10,13,15,-1,-1},{10,-1,14,-1,-1,-1} }; int n; struct point { int s; int num; int time; int path[2][15]; }; queue<point> q; set<int> Set; void bfs() { Set.clear(); while(!q.empty()) q.pop(); point tmp; tmp.s = ((1 << 16) - 1)^(1 << (n - 1)); tmp.time = 0; tmp.num = 14; q.push(tmp); while(!q.empty()) { point a = q.front(); q.pop(); for(int i = 0; i < 15; i++) { if(a.s & (1 << i)) { for(int j = 0; j < 6; j++) { int cur = i; point c = a; if(jump[i][j] != -1 && c.s & (1 << (jump[i][j] - 1))) { while(cur >= 0 && (c.s & (1 << cur))) { c.s ^= (1 << cur); c.num--; cur = jump[cur][j] - 1; } if(cur < 0) continue; c.s |= (1 << cur); c.path[0][c.time] = i + 1; c.path[1][c.time] = cur + 1; c.time++; c.num++; if(!Set.count(c.s)) { if(c.num == 1 && c.s & (1 << (n - 1))) { printf("%d\n%d %d",c.time,c.path[0][0],c.path[1][0]); for(int k = 1; k < c.time;k++) { printf(" %d %d",c.path[0][k],c.path[1][k]); } printf("\n"); return; } Set.insert(c.s); q.push(c); } } } } } } printf("IMPOSSIBLE\n"); } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d",&n); bfs(); } }
标签:uva
原文地址:http://blog.csdn.net/yeyeyeguoguo/article/details/45199457