思路
普通bfs思路,建立一个Node,里面包含空格位置,当前序列,和前置序列。
这道题主要点是map<string,bool>这个,这里的map不是用string的地址做映射,而是用string的值做映射的(开始我还以为静态字符串和动态生成的字符串在对map做映射时会有区别,惭愧惭愧)。
但是如果用普通的map会导致超时,是因为map内部时刻有序红黑树,所以建立起来非常简单,但是查询相对麻烦,与之对应的unordered_map则是建立比较困难,但是查询相当简单。
还有一个点就是,vector竟然可以直接赋值???还有string类型,在赋值之后竟然还可以修改???长见识了。
还有就是不知道蓝桥杯能不能用unordered_map
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;
struct Node{
string status;
int pos;
vector<int> step;
Node(){};
Node(string str,int p){
status=str;
pos=p;
}
};
string _swap(string s,int a,int b){
string t=s;
char c=s[a];
t[a]=s[b];
t[b]=c;
return t;
}
unordered_map <string,bool> mp;
int main(){
int N;
scanf("%d",&N);
string st,se;//正向,逆向字符串
for(int i=0;i<N;i++){
st=st+'1';
se=se+'2';
}
st=st+'0';
se=se+'0';
for(int i=0;i<N;i++){
st=st+'2';
se=se+'1';
}
Node first;
first=Node(st,N);
first.step.push_back(N);
queue<Node> qe;
int dx[]={-2,-1,1,2};
qe.push(first);
while(!qe.empty()){
Node temp=qe.front();
qe.pop();
if(temp.status==se){
int cnt=0;
for(int i=1;i<temp.step.size();i++){
if(cnt==4){
printf("%d\n",temp.step[i]+1);
cnt=0;
}
else{
printf("%d ",temp.step[i]+1);
cnt++;
}
}
return 0;
}
for(int i=0;i<4;i++){
int next_pos=temp.pos+dx[i];
if(next_pos>=0&&next_pos<N*2+1){
string next_status=_swap(temp.status,temp.pos,next_pos);
if(!mp[next_status]){
mp[next_status]=true;
Node ssx;
ssx=Node(next_status,next_pos);
ssx.step=temp.step;
ssx.step.push_back(next_pos);
qe.push(ssx);
}
}
}
}
return 0;
}