HDU1043-Eight(BFS +康托展开)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1043

题目大意:一个3 *3的地图。装着1-9这9个数,问你能不能只移动9(上下左右),到达题目所给的状态。(简便起见,我直接把输入的x变为9了)

解题思路:把一个状态用一个9位数来保存,让后逆向思维从123456789来开始bfs,记录每一个路径。输出答案的时候倒序输出就行了。然而这样空间显然是不够的,所以这题可以用到康托展开来转换一下。

还有就是注意一下细节。

AC Code:

(时限给了5s,实际上200+ms就能过了)

//My Conquest Is the Sea of Stars.
#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<cstdio>
#include<string>
#include<vector>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<algorithm>
#define fi first
#define se second
#define gcd __gcd
#define pb push_back
#define mp make_pair
#define lowbit(x) x & (-x)
#define PII  pair<int, int> 
#define all(x) x.begin(), x.end()
#define rep(i, a, b) for(int i = a; i <= (b); i++)
#define FAST ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = (int)1e9 + 7;
const int maxn = (int)370000;
using namespace std;

const int fac[15] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
const int dir[4] = {3, 1, -3, -1};
string ans[maxn];
string go = "uldr";

inline int cantor(int *a){
	int ret = 0;
	rep(i, 0, 8){
		int cnt = 0;
		rep(j, i + 1, 8){
			if(a[j] < a[i]) cnt++;
		}
		ret += fac[9-i-1] * cnt;
	}
	return ret;
}

bool vis[maxn];

void bfs(){
	queue<int> q;
	q.push(123456789);
	vis[0] = 1;
	while(!q.empty()){
		int now = q.front();
		q.pop();
		int pos, num = now;
		int a[15];
		for(int i = 8; i >= 0; i--){
			if(num % 10 == 9) pos = i;
			a[i] = num % 10;
			num /= 10;
		}
		int cur = cantor(a);
		rep(i, 0, 3){
			if(pos == 0 && (i == 2 || i == 3)) continue;
			else if(pos == 1 && i == 2) continue;
			else if(pos == 2 && (i == 1 || i == 2)) continue;
			else if(pos == 3 && i == 3) continue;
			else if(pos == 5 && i == 1) continue;
			else if(pos == 6 && (i == 0 || i == 3)) continue;
			else if(pos == 7 && (i == 0)) continue;
			else if(pos == 8 && (i == 1 || i == 0)) continue;
			int t = pos + dir[i];
			int next = 0;
			swap(a[t], a[pos]);
			rep(j, 0, 8) next *= 10, next += a[j];
			int temp = cantor(a);
			if(!vis[temp]){
				q.push(next);
				vis[temp] = 1;
				ans[temp] = ans[cur] + go[i];
			}
			swap(a[t], a[pos]);
		}
	}
}

int main()
{
	bfs();
	char in[10];
	while(~scanf(" %c", &in[0])){
		rep(i, 1, 8) { scanf(" %c", &in[i]); if(in[i] == 'x') in[i] = '9'; }
		int temp[15];
		rep(i, 0, 8) temp[i] = in[i] - '0';
		int t = cantor(temp);
		if(!vis[t]) puts("unsolvable"); 
		else {
			int len = ans[t].size();
			for(int i = len - 1; i >= 0; i--) cout << ans[t][i];
			cout << endl;
		}
	}
	return 0;
}

总感觉代码有可以改进的地方,懒得改了。

over

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值