HDU 1043、POJ 1077

在HDU无压力过,在POJTLE。。。。
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
using namespace std;

int vis[1000000];
int dir[1000000][2];
queue< vector<short> > q;
queue<int> zt; 
int start;
int target;

const int dx[] = {
	-1, 1, 0 ,0
};

const int dy[] = {
	0, 0, -1, 1
};

int fac[9] = {
	0, 1, 2, 6, 24, 120, 720, 5040, 40320 
};

int kt(vector<short> &temp)
{
	int re = 1;
	int hash[9] = {
		0,0,0,0,0,0,0,0,0
	};
	for(int i = 0; i < 8; i++){
		hash[temp[i]] = 1;
		
		int number = 0;
		for(int j = temp[i]-1; j >= 0; j--)
			if(!hash[j])
				number++;
		re += fac[8-i]*number;
	}
	return re;
}

int main()
{
	char temp, counter = 0;
	
	
		vector<short> vtemp;
		vtemp.push_back(1);vtemp.push_back(2);vtemp.push_back(3);
		vtemp.push_back(4);vtemp.push_back(5);vtemp.push_back(6);
		vtemp.push_back(7);vtemp.push_back(8);vtemp.push_back(0);
		
		zt.push(kt(vtemp));
		vis[zt.front()] = 1;
		target = zt.front();
		q.push(vtemp);
		while(!q.empty()){
			vector<short> rear = q.front();
			q.pop();
			int r = zt.front();
			zt.pop();
			
			int z;
			for(z = 0; z < 9; z++)
				if(!rear[z])
					break;
			int x = z/3, y = z%3;
			
			int newx, newy, newz;
			for(int i = 0; i < 4; i++){
				newx = x + dx[i];
				newy = y + dy[i];
				newz = newx*3 + newy;
				if(newx >= 0 && newx < 3 && newy >= 0 && newy < 3){
					vector<short> newv(rear);
					int temp = newv[z];
					newv[z] = newv[newz];
					newv[newz] = temp;
					
				    int newr = kt(newv);
				    if(!vis[newr]){
				    	vis[newr] = 1;
    					zt.push(newr);
    					dir[newr][0] = r;
    					dir[newr][1] = i;
    					q.push(newv);
					}
				}
			}
		}

	while(cin >> temp){
		vector<short>vtemp;
		vtemp.push_back(temp == 'x' ? 0 : temp - '0');
		for(int i = 1; i < 9; i++){
			cin >> temp;
 			if(temp >= '1' && temp <= '8'){
				vtemp.push_back(temp-'0');
			}else
				vtemp.push_back(0);
		}
		start = kt(vtemp);
		bool isanswer = false;
		if(vis[start])
			isanswer = true;
			
		if(isanswer){
			int now = start;
			stack<char> out;
			while(now != target){
				switch(dir[now][1]){
					case 0: cout << "d"; break;
					case 1: cout << "u"; break;
					case 2: cout << "r"; break;
					case 3: cout << "l";
				}
				now = dir[now][0];
			}
			while(!out.empty()){
				cout << out.top();
				out.pop();
			}
			cout << endl;
		}else{
			cout << "unsolvable" << endl;
		}
	}
	return 0;	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值