HDU 1043 全排列 康托展开

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值