牛客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;
}
发布了411 篇原创文章 · 获赞 72 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/Flynn_curry/article/details/104848796