牛客oj 习题9.1 玛雅人的密码(BFS)

 

 

BFS大水题。由于有两个2、一个1、一个0的字符串中经过有限次移位后必定会得到2012,所以只有这些元素不够的情况会出现解不开密码。剩下的也没什么好说的,就是移位后判断如果没有2012就入队。

 

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <climits>
 
using namespace std;
 
const int MAXN = 20000;
const int INF = INT_MAX;

string str;

struct Sample{
	string content;
	int time;
	Sample(string c, int t) : content(c), time(t) {} 
};

void change(char &x, char &y){
	char tmp = x;
	x = y;
	y = tmp;
}

int bfs(){
	queue<Sample> myqueue;
	myqueue.push(Sample(str, 0));
	while(!myqueue.empty()){
		Sample sample = myqueue.front();
		myqueue.pop();
		int len = sample.content.size();
		for(int i = 0; i < len-1; i++){
			string tmpc = sample.content;
			int tmpt = sample.time;
			change(tmpc[i], tmpc[i+1]);
			tmpt++;
			if(tmpc.find("2012") != string::npos) return tmpt;
			myqueue.push(Sample(tmpc, tmpt));
		}
	}
}

int main(){
  //  freopen("in.txt", "r", stdin);
    int n;
	while(~scanf("%d", &n)){
		cin >> str;
		int two = 0, zero = 0, one = 0;
		for(int i = 0; i < str.size(); i++){
			if(str[i] == '2') two++;
			else if(str[i] == '1') one++;
			else if(str[i] == '0') zero++;
		}
		if(two < 2 || zero < 1 || one < 1) printf("-1\n");
		else if(str.find("2012") != string::npos) printf("0\n");
		else cout << bfs() << endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值