跳到正文

算法·理论

笔记

bitset_hard约 13 分钟
原文

这是 2026年2月7日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

枚举&模拟

  • 通过挖掘题目的特殊性质,找到分析问题的切入点
  • 更换统计答案的方式
  • 特殊性质优化
  • 模型等效替换

深度优先搜索(depth first search,dfs)

适用问题:

能把待求解的问题分成不太多的步骤,每个步骤又只有不太多的选择。

模板:

C++
void dfs(int dep,...){//正在完成问题的第dep步
	如果已经完成最后一步,则返回;
	完成第dep步; 
	dfs(dep+1,...); 
} 

它的本质上是一种走不通就掉头的思想。有些问题在往下一步搜索时,每一步都出现很多分支,为了求得问题的解,我们必须对每一个分支都要试探,看看是否符合题目要求,若发现某一步试探不合要求,则停止从该分支往下的试探,立即返回到上一步去试探其它分支,直到找到问题的解。如果回溯到问题的初始状态之后还要返回,则表示该问题无解。

  • 剪枝

1.可行性剪枝
在搜索的过程中,及时对当前状态进行检查,如果发现分支已经无法到达递归边界,就执行回溯。这就好比我们在路上走时,远远看到前方是一个死胡同,就应该立即折返绕路,而不是走到路的尽头再返回。
2.上下界剪枝
在最优化问题的搜索过程中,如果当前花费的代价已经超过当前搜到的最优解,那么无论采取多么优秀的策略到达递归边界,都不可能更新答案。此时可以停止对当前分支的搜索,执行回溯,本质上就是考虑极端情况。
例题:P1219八皇后

AC code
C++
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 35;
int n,ans,a[MAXN];
bool vis[3][MAXN] = {0};
void print(){
    for(int i = 1;i <= n;++i){
        printf("%d ",a[i]);
    }
    cout << endl;
}
void search(int i){
    if(i == n + 1){
        ans++;
        if(ans <= 3)
            print();
        return ;
    }
    for(int j = 1;j <= n;++j)
        if(!vis[0][j] && !vis[1][i + j] && !vis[2][i - j + n - 1]){
            a[i] = j;
            vis[0][j] = vis[1][i + j] = vis[2][i - j + n - 1] = 1;
            search(i + 1);
            vis[0][j] = vis[1][i + j] = vis[2][i - j + n - 1] = 0;
        }
}
int main(){
    cin >> n;
    search(1);
    printf("%d\n",ans);
    return 0;
}
  • 回溯

每次递归进入深一层,进行标记;从深层返回后,清除标记。这个方法就叫做回溯。

  • 洪水填充(floodfiil)

例题P1451 求细胞数量

AC Code
C++
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 105;
int m,n;
char field[MAXN][MAXN];
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
int colorCount;
void floodfill(int x,int y){
    field[x][y] = 0;
    for(int k = 0;k < 4; ++k){
        int xx = x + dx[k];
        int yy = y + dy[k];
        if(xx > 0 && xx <= m && yy > 0 && yy <=n){
            if(field[xx][yy]>='1' && field[xx][yy] <='9')
                floodfill(xx,yy);
        }
    }
}
int main(){
    cin>>m>>n;
    for(int i = 1;i <= m;++i){
        for(int j = 1;j <= n; ++j){
            cin>>field[i][j];
        }
    }
    for(int i=1;i<=m;++i){
        for(int j=1;j<=n;++j){
            if(field[i][j]>='1'&&field[i][j]<='9'){
                colorCount++;
                floodfill(i,j);
            }
        }
    }
    cout<<colorCount<<endl;
    return 0;
}

广度优先搜索算法(breadth first search,bfs)

特点:先尝试在本层枚举,如果本层没有答案,则去下一层枚举下一层的所有可能性。

模板:

C++
void bfs()
{
	初始结点入队
	记录状态
	while(队列非空)
	{
		取出队首元素u
		遍历所有相邻且还未访问过的元素v
		{
			将v点加入队列
			记录状态
			如果v点为目标结点,返回相关信息。结束。 
		 } 
		u点出队
	} 
 } 

例题:P1443 马的遍历

AC Code
C++
#include<bits/stdc++.h>
using namespace std;
int n,m,x,y;
int board[405][405];
int dx[] = {-2,-2,-1,-1,1,1,2,2};
int dy[] = {-1,1,-2,2,-2,2,-1,1};

void bfs(int startX,int startY){
    memset(board,-1,sizeof(board));
    queue<int>q;
    q.push(startX);
    q.push(startY);
    board[startX][startY] = 0;
    while(!q.empty()){
        int x = q.front();
        q.pop();
        int y = q.front();
        q.pop();
        for(int i = 0; i < 8;++i){
            int xx = x + dx[i];
            int yy = y + dy[i];
            if(xx > 0 && xx <= n && yy > 0 && yy <= m && board[xx][yy] == -1){
                board[xx][yy] = board[x][y] + 1;
                q.push(xx);
                q.push(yy);
            }
        }
    }
}
int main(){
    scanf("%d%d%d%d",&n,&m,&x,&y);
    bfs(x,y);
    for(int i = 1;i <= n;++i){
        for(int j = 1;j <= m;++j){
            printf("%-5d",board[i][j]);
        }
        printf("\n");
    }
    return 0;
}

下面看一个二维的例子:P1141 01迷宫

AC Code
C++
#include<bits/stdc++.h>
using namespace std;
int maze[1005][1005];
int color[1005][1005];
int n,m;
int nextColor;
int colorCount[1000005];
const int dx[4] = {0,1,0,-1};
const int dy[4] = {1,0,-1,0};

int bfs(int x,int y){
    if(color[x][y] != -1){
        return colorCount[color[x][y]];
    }
    int count = 1;
    queue<int>q;
    color[x][y] = nextColor;
    q.push(x);
    q.push(y);
    while(!q.empty()){
        x = q.front();
        q.pop();
        y = q.front();
        q.pop();
        for(int i = 0; i < 4;++i){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(!(nx > 0 && nx <= n && ny > 0 && ny <= n))continue;
            if(color[nx][ny] == -1 && maze[nx][ny] != maze[x][y]){
                color[nx][ny] = nextColor;
                count++;
                q.push(nx);
                q.push(ny);
            }
        }
    }
    colorCount[nextColor] = count;
    nextColor++;
    return count;
}
int main(){
    cin >> n >> m;
    for(int i = 1;i <= n;++i){
        for(int j = 1; j <= n;++j){
            char c;
            cin >> c;
            maze[i][j] = c - '0';
        }
    }
    memset(color,-1,sizeof(color));
    nextColor = 0;
    for(int i = 0;i < m;++i){
        int x,y;
        cin >> x >> y;
        cout << bfs(x,y) << endl;
    }
    return 0;
}

接下来是一个复杂一点的问题 P1379 八数码难题

AC Code
C++
#include<bits/stdc++.h>
using namespace std;
struct Step{
    int num;
    string status;
    int x,y;
};
int dx[] = {-1,1,0,0};
int dy[] = {0,0,-1,1};

int main(){
    string start;
    string end = "123804765";
    cin >> start;
    queue<Step> q;
    for(int i = 0;i <= 8;++i){
        if(start[i] == '0'){
            int x = i / 3;
            int y = i % 3;
            q.push({0,start,x,y});
        }
    }
    set<string>s;
    s.insert(start);
    while(!q.empty()){
        Step p = q.front();
        q.pop();
        if(p.status == end){
            cout << p.num << endl;
            return 0;
        }
        string t = p.status;
        int x = p.x;
        int y = p.y;
        int pos = x * 3 + y;
        for(int k = 0;k < 4;++k){
            int xx = x + dx[k];
            int yy = y + dy[k];
            if(xx >= 0 && xx <= 2 && yy >= 0 && yy <= 2){
                int nextpos = xx * 3 + yy;
                swap(t[pos],t[nextpos]);
                if(s.count(t) == 0){
                    q.push({p.num + 1,t,xx,yy});
                    s.insert(t);
                }
                swap(t[pos],t[nextpos]);
            }
        }
    }
    return 0;
}