您的位置:首页 > 其它

HDU 1043 全排列 康托展开

2017-07-17 17:15 218 查看
#include <bits/stdc++.h>

#define lowbit(x) (x&(-x))
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;

#define sp system("pause")

int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
char t[4] = {'l','r','u','d'};

int pre[400000];
int tn[400000];
int f[12];
const int maxn = 12;

int n = 9;

void init()
{
f[0] = 1;
for (int i = 1; i <= 10; i++)f[i] = f[i - 1] * i;
memset(pre, -1, sizeof pre);
}

void intToArray(int x, int a[])
{
bool used[maxn];
int i, j, temp;
for (i = 1; i <= n; i++)used[i] = false;
for (i = 1; i <= n; i++)
{
temp = x / f[n - i];
for (j = 1; j <= n; j++)
{
if (!used[j])
{
if (!temp)break;
temp--;
}
}
a[i] = j;
used[j] = true;
x %= f[n - i];
}
}

int arrayToInt(int a[])
{
int ans, i, j, temp;
ans = 0;
for (i = 1; i <= n; i++)
{
temp = a[i] - 1;
for (j = 1; j < i; j++)if (a[j] < a[i])temp--;
ans += f[n - i] * temp;
}
return ans;
}

int la[12], lb[12];

struct node
{
int now, sx, sy;
node(int aa = 0, int bb = 0, int cc = 0)
{
now = aa, sx = bb, sy = cc;
}
};

int main()
{
init();
for (int i = 1; i <= 9; i++)la[i] = i;
pre[0] = 0;
queue<node>q;

q.push(node(0,2,2));
while (q.size())
{
node t = q.front();
q.pop();
intToArray(t.now, lb);
int sx, sy;
//for (int i = 1; i <= 9; i++)if (lb[i] == 9)sx = i;
sy = t.sy;
sx = t.sx;
for (int i = 0; i < 4; i++)
{

int tx = sx + dx[i], ty = sy + dy[i];
if (tx<0 || tx>2 || ty<0 || ty>2)continue;
swap(lb[tx * 3 + ty + 1], lb[sx * 3 + sy + 1]);
int now = arrayToInt(lb);
if (pre[now] == -1)
{
pre[now] = t.now;
tn[now] = i;
q.push(node(now,tx,ty));
}
swap(lb[tx * 3 + ty + 1], lb[sx * 3 + sy + 1]);
}
}

char s[2];
while (scanf("%s", s) != EOF)
{
if (s[0] == 'x')s[0] = '9';
la[1] = s[0] - '0';
for (int i = 2; i <= 9; i++)
{
scanf("%s", s);
if (s[0] == 'x')s[0] = '9';
la[i] = s[0] - '0';
}
int now = arrayToInt(la);
if (pre[now] == -1)puts("unsolvable");
else
{
while (now != 0)
{
printf("%c", t[tn[now]]);
now = pre[now];
}
printf("\n");
}
}

//	sp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: