0x27 搜索-A* 题目链接
这道题,并没有用A*然后就给过去了,主要是牛客的测评机的,又快又好用!
直接暴力加上康托展开,然后就给过了,虽然实际上在杭电以及POJ上都会被卡内存或者是空间,所以仍然需要优化才行。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 10, maxP = 363000;
const char the_way[4] = { 'd', 'r', 'l', 'u' };
const int dir[4][2] =
{
-1, 0,
0, -1,
0, 1,
1, 0
};
inline int _id(int x, int y) { return (x - 1) * 3 + y - 1; }
inline bool In_map(int x, int y) { return x > 0 && y > 0 && x <= 3 && y <= 3; }
int tree[maxN], jc[maxN];
inline void add(int x)
{
if(x == 0) return;
while(x <= 9) { tree[x]++; x += lowbit(x); }
}
inline int sum(int x)
{
int ans = 0;
while(x) { ans += tree[x]; x -= lowbit(x); }
return ans;
}
inline int Cantor(int len, int *a)
{
memset(tree, 0, sizeof(tree));
int ans = 0, tmp;
for(int i=len-1; i>=0; i--)
{
tmp = sum(a[i] + 1);
ans += tmp * jc[len - i - 1];
add(a[i] + 1);
}
return ans + 1;
}
bool vis[maxP];
string out[maxP];
struct node
{
int a[maxN];
int x, y;
};
inline void bfs()
{
memset(vis, false, sizeof(vis));
queue<node> Q;
node now, to;
for(int i=0; i<8; i++) now.a[i] = i + 1;
now.a[8] = 0;
now.x = now.y = 3;
int sta = Cantor(9, now.a), las;
Q.push(now);
vis[sta] = true;
out[sta] = "";
while(!Q.empty())
{
now = Q.front(); Q.pop();
sta = Cantor(9, now.a);
for(int i=0, xx, yy; i<4; i++)
{
xx = now.x + dir[i][0]; yy = now.y + dir[i][1];
if(!In_map(xx, yy)) continue;
to = now;
swap(to.a[_id(now.x, now.y)], to.a[_id(xx, yy)]);
to.x = xx; to.y = yy;
las = Cantor(9, to.a);
if(!vis[las])
{
vis[las] = true;
out[las] = out[sta] + the_way[i];
Q.push(to);
}
}
}
}
char ch[10][3];
int num[10];
int main()
{
jc[0] = jc[1] = 1;
for(int i=2; i<10; i++) jc[i] = jc[i-1] * i;
bfs();
while(scanf("%s", ch[0]) != EOF)
{
for(int i=1; i<9; i++) scanf("%s", ch[i]);
for(int i=0; i<9; i++)
{
if(ch[i][0] >= '1' && ch[i][0] <= '9') num[i] = ch[i][0] - '0';
else num[i] = 0;
}
int tmp = Cantor(9, num);
if(!vis[tmp]) printf("unsolvable\n");
else
{
int len = (int)out[tmp].size();
for(int i=len-1; i>=0; i--) printf("%c", out[tmp][i]);
printf("\n");
}
}
return 0;
}