计蒜客 一维跳棋

在这里插入图片描述

思路

普通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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值