蓝桥杯 历届试题 青蛙跳杯子

11 篇文章 0 订阅
10 篇文章 0 订阅

题目:青蛙跳杯子

问题描述

X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。

*WWWBBB

其中,W字母表示白色青蛙,B表示黑色青蛙,*表示空杯子。

X星的青蛙很有些癖好,它们只做3个动作之一:
1. 跳到相邻的空杯子里。
2. 隔着1只其它的青蛙(随便什么颜色)跳到空杯子里。
3. 隔着2只其它的青蛙(随便什么颜色)跳到空杯子里。

对于上图的局面,只要1步,就可跳成下图局面:

WWW*BBB

本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。

输入为2行,2个串,表示初始局面和目标局面。
输出要求为一个整数,表示至少需要多少步的青蛙跳。

样例输入
*WWBB
WWBB*

样例输出
2

样例输入
WWW*BBB
BBB*WWW

样例输出
10

数据规模和约定
我们约定,输入的串的长度不超过15

峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms

 

思路:感觉这题和第八届省赛C++A组的跳蚱蜢完全一样的思路,用bfs搜索空杯子向6个方向移动的情况,用map来查重。

代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>  
#include<set>
using namespace std;

struct node
{
	string s;
	int step;
	node(string ss,int st)
	{
		s=ss;
		step=st;
	} 
};
int dir[6]={-3,-2,-1,1,2,3},len;
string s,t;
map<string,int>m;
queue<node>q;

void bfs()
{
	int find=0;
	m[s]=1;
	q.push(node(s,0));
	while(find!=1)
	{
		node x=q.front();
		int i,temp;
		for(i=0;i<15;i++)
		{
			if(x.s[i]=='*')
			{
				temp=i;
				break;
			}
		}
		for(i=0;i<6;i++)
		{
			if(temp+dir[i]>=0&&temp+dir[i]<=len)
			{
				x.s[temp]=x.s[temp+dir[i]];
				x.s[temp+dir[i]]='*';
				if(!m[x.s])
				{
					if(x.s==t)
					{
						find=1;
						cout<<x.step+1<<endl;
					}
					m[x.s]=1;
					q.push(node(x.s,x.step+1));
				}
				x.s[temp+dir[i]]=x.s[temp];
				x.s[temp]='*';
			}
		}
		q.pop();
	}
}
int main()
{
	cin>>s>>t;
	len=s.length()-1;
	bfs();
	return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值