【例 7-12 UVA - 1343】The Rotation Game

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

迭代加深搜索。 每次抽动操作最多只会让中间那一块的区域离目标的“距离”减少1. 以这个作为剪枝。 枚举最大深度。 就能过了。

【代码】

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;

const int N = 10;

int b[N][N] = { { 1, 3, 7, 12, 16, 21, 23 }, { 2, 4, 9, 13, 18, 22, 24 }, { 11, 10, 9, 8, 7, 6, 5 }, { 20, 19, 18, 17, 16, 15, 14 } };
int fan[N];
int a[30];
int c[N + 5] = { 7, 8, 9, 12, 13, 16, 17, 18 };
int maxdep, ans;
vector <int> v, vans;

void init(){
	for (int i = 0; i < 4; i++){
		int temp;
		if (i & 1) temp = 3; else temp = 5;
		int j = i + temp;
		fan[i] = j;
		fan[j] = i;
	}
	for (int i = 4; i < 8; i++){
		int pre = fan[i];
		int now = 0;
		for (int j = 6; j >= 0; j--){
			b[i][now] = b[pre][j];
			now++;
		}
	}
}

int ok(){
	int mi = 8;
	for (int i = 1; i <= 3; i++){
		int cnt = 0;
		for (int j = 0; j < 8; j++) if (a[c[j]] != i) cnt++;
		mi = min(mi, cnt);
	}
	return mi;
}

void Move(int idx){
	int temp = a[b[idx][0]];
	for (int i = 0; i < 6; i++){
		int x = b[idx][i], y = b[idx][i + 1];
		a[x] = a[y];
	}
	a[b[idx][6]] = temp;
}

void dfs(int dep){
	if (ans != 0) return;
	int now = ok();
	if (dep == maxdep){
		if (now == 0){
			vans = v;
			ans = a[c[0]];
		}
		return;
	}
	int rest = maxdep - dep;
	if (rest < now) return;
	for (int i = 0; i < 8; i++){
		v.push_back(i);
		Move(i);
		dfs(dep + 1);
		v.pop_back();
		Move(fan[i]);
	}
}

int main()
{
	#ifdef LOCAL_DEFINE
	    freopen("F:\\c++source\\rush_in.txt", "r", stdin);
	#endif
	ios::sync_with_stdio(0), cin.tie(0);
	init();
	while (cin >> a[1] && a[1]){
		for (int i = 2; i <= 24; i++) cin >> a[i];
		if (ok() == 0){
			cout << "No moves needed" << endl;
			cout << a[c[0]] << endl;
			continue;
		}

		ans = 0;
		for (maxdep = 1;; maxdep++){
			dfs(0);
			if (ans != 0) break;
		}
		for (int i = 0; i<(int)vans.size(); i++){
			cout << (char)(vans[i] + 'A');
		}
		cout << endl;
		cout << ans << endl;
	}
	return 0;
}
posted @ 2017-12-14 11:01  AWCXV  阅读(149)  评论(0编辑  收藏  举报