目录
搜索问题
深度优先搜索
翻转开关问题
迭代加深搜索
埃及分数问题
广度优先搜索
双向广度优先搜索

八数码问题

#include <iostream>
#include <string>
#include <queue>
#include <map>
using namespace std;
//记录该string状态处于正(反)向的第几层BFS
map<string, int>fsign, rsign;
int fcnt[300000];
int rcnt[300000];
string aim = "123804765";
//1:up,2:down,3:left,4:right
int moveto(int i, int index) {
switch (i) {
case 1:
if (index - 3 >= 0)return index - 3;
break;
case 2:
if (index + 3 <= 8)return index + 3;
break;
case 3:
if (index % 3 != 0)return index - 1;
break;
case 4:
if (index % 3 != 2)return index + 1;
break;
}
return -1;
}
bool extend(queue<string>&q, int head, int &tail, int direction) {
string now = q.front(); q.pop();
int from = now.find('0');
for (int i = 1; i <= 4; i++) {
int to = moveto(i, from);
if (to != -1) {
swap(now[from], now[to]);
if (direction == 1) { //up to dowm
if (!fsign[now]) { // not visited yet
q.push(now);
fsign[now] = fcnt[tail++] = fcnt[head] + 1;
if (rsign[now]) {
cout << fcnt[tail - 1] + rsign[now] << endl;
return true;
}
}
}
else {// down to up
if (!rsign[now]) {
q.push(now);
rsign[now] = rcnt[tail++] = rcnt[head] + 1;
if (fsign[now]) {
cout << rcnt[tail - 1] + fsign[now] << endl;
return true;
}
}
}
swap(now[from], now[to]);
}
}
return false;
}
void DBFS(string start) {
if (start.compare(aim) == 0) {
cout << '0' << endl;
return;
}
bool flag = false;
queue<string>forward, reverse;
forward.push(start);
reverse.push(aim);
string forwardNow = start, reverseNow = aim;
fsign[start] = 0; rsign[aim] = 0;
int head = 0, tail = 1, rhead = 0, rtail = 1;
while (!flag) {
if (forward.size() <= reverse.size()) { // choose the shorter one
if (extend(forward, head, tail, 1))return;
head++;
}
else {
if (extend(reverse, rhead, rtail, 2))return;
rhead++;
}
}
}
int main() {
string start;
cin >> start;
DBFS(start);
return 0;
}
动态规划
一维递推问题(求和形式)
爬楼梯

一维递推问题(最值形式)
数字三角形

动态规划详解(数字三角形POJ1163)_ancientear的博客-CSDN博客_数字三角形动态规划
最长上升子序列


本文详细介绍了搜索问题中的深度优先和广度优先搜索,特别是迭代加深搜索和双向广度优先搜索。接着深入探讨了动态规划的各种应用场景,包括一维和二维问题的递推解法。此外,还讲解了分治策略中的快速排序,贪心算法的第K大数问题,以及矩阵快速幂等高效计算方法。文章最后提到了随机算法中的拉斯维加斯算法和蒙特卡洛算法在解决最小割问题上的应用。
最低0.47元/天 解锁文章
255

被折叠的 条评论
为什么被折叠?



