1318: [蓝桥杯2017初赛]跳蚱蜢

1318: [蓝桥杯2017初赛]跳蚱蜢

思路:状态压缩,把开始的序列012345678看成123456789, 结尾序列087654321看成198765432,就很容易做了,能进行的操作也就是四个,设1在进行左右跳动,直接和相邻的交换或者隔一个交换,可以用一个数组来表示这个操作,用bfs来寻找最段路径,之后看代码把,不难

#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h> 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i < (int)n; i++)
#define per(i, a, n) for(int i = (int)n-1; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline int read(){
	int x=0,f=1;char ch=getchar();
	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
	while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
	return x*f;
}
struct node
{
	int x, y, z;	//x表示当前的数是多少,y表示空位在哪里,(这个可有可无),z表示当前走的步数
};
unordered_map<int, int> m;
int check(int num, int x, int y){	//num表示当前的数,x表示当前的空位,y表示要跳到的位置
	int a[9];
	int j = 8;
	while(num){
		a[j] = num%10;
		num /= 10;
		j--;
	}
	a[x] = a[y], a[y] = 1;
	int res = 0;
	for(int i = 0; i < 9; i++){
		res += a[i]*pow(10, 8-i);
	}
	return res;
}
int dir[4] = {1,2,-1,-2};
void bfs(){
	queue<node> q;
	q.push({123456789,0,0});
	m[123456789] = 1;
	while(!q.empty()){
		node tmp = q.front();q.pop();
		if(tmp.x==198765432){
			printf("%d\n", tmp.z);
			break;
		}
		for(int i = 0; i < 4; i++){
			int x = (tmp.y+dir[i]+9)%9;
			int y = check(tmp.x, tmp.y, x);
			if(!m[y]){
				q.push({y, x, tmp.z+1});
				m[y] = 1;
			}
		}
	}
}
signed main(){
	bfs();
	return 0;
}	
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值