HzuWHF


私信TA

用户名:I7I08I9047

访问量:76472

签 名:

我RUN了

等  级
排  名 18
经  验 20464
参赛次数 13
文章发表 127
年  龄 3
在职情况 学生
学  校 贺州学院
专  业

  自我简介:

解题思路:

        BFS + Hash。Hash 用来记录某个状态是否走过。广搜每次都与相邻位置交换入列即可。


参考代码:

#include<bits/stdc++.h>
using namespace std;
 
int Len;
bool Vis[31309];
typedef struct {
	string Pass; int Step;
} status;
queue<status> que;

bool find(string Pass) {
	if (Pass.find("2012") == string::npos)
		return false;
	return true;
}

int Hash(string Pass) {
	int hash = 0;
	for (int i = 0; i < Len; i++)
		hash += hash * 2 + Pass[i] - 41;
	return hash % 29231;
}

int BFS() {
	while (!que.empty()) {
		status now = que.front(); que.pop();
		for (int pos = 0; pos < Len - 1; pos++) {
			swap(now.Pass[pos], now.Pass[pos + 1]); 
			now.Step++;

			if (find(now.Pass))
				return now.Step;
			int hashValue = Hash(now.Pass);
			if (!Vis[hashValue]) {
				Vis[hashValue] = true; que.push(now);
			}
			now.Step--;
			swap(now.Pass[pos], now.Pass[pos + 1]);
		}
	}
	return -1;
}

int main() {
	status start; start.Step = 0;
	cin >> Len >> start.Pass;
	if (start.Pass.find("2012") == string::npos) {
		que.push(start); cout << BFS();
	}
	else cout << 0;
}


 

0.0分

4 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区