AOJ 0121 bfs + dp

58 篇文章 0 订阅
题意

传送门 AOJ 0121

直接 bfs 复杂度达到搜索深度的指数级,结合 dp 用 bfs 打表,每次保存 0 的位置,通过交换字符位置进行状态转移。

#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
#include <string>
#define min(a,b)    (((a) < (b)) ? (a) : (b))
#define max(a,b)    (((a) > (b)) ? (a) : (b))
#define abs(x)    ((x) < 0 ? -(x) : (x))
#define INF 0x3f3f3f3f
#define delta 0.85
#define eps 1e-3
#define PI 3.14159265358979323846
using namespace std;
struct st{
	int p;
	string s;
	st(int p, string s) : p(p), s(s) {}
};
const int dx[4] = {4, -4, 1, -1};
map<string, int> dp;

bool judge(int x, int d){
	if((x == 3 && d == 1) || (x == 4 && d == -1)) return 0;
	x += d;
	return x >= 0&& x <= 7;
}

void bfs(){
	queue<st> que;
	string f = "01234567";
	dp[f] = 0;
	que.push(st(0, f));
	while(!que.empty()){
		st now = que.front(); que.pop();
		int x = now.p;
		for(int i = 0; i < 4; i++){
			if(judge(x, dx[i])){
				int nx = x + dx[i];
				string s = now.s;
				swap(s[x], s[nx]);
				if(dp.find(s) == dp.end()){
					dp[s] = dp[now.s] + 1;
					que.push(st(nx, s));
				}
			}
		}
	}
}

int main(){
	bfs();
	string s;
	while(getline(cin, s)){
		s.erase(remove(s.begin(), s.end(), ' '), s.end());
		cout << dp[s] << endl;
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值