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;
}
2149

被折叠的 条评论
为什么被折叠?



