2025.07.08课堂总结

· · 个人记录

2025.07.08课堂总结

重点一

首先围绕昨天剩下的深搜题P1088 [NOIP 2004 普及组] 火星人为基础,重新复习了深搜,并提供了一个新思路:解决深搜全排列问题时可以视情况使用修改起点的方法。
代码:

#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
int n, m, ans[10005], t[10002], cnt = 0;
bool vis[10005];
int f = 0;

// 递归枚举全排列,找到第m+1个排列(初始排列为第1个)
void dfs(int cur){
    if(cur > n)
    {
        f = 1;
        if (f == 1)
        {
            cnt++;
            // 找到第m+1个排列时输出并退出
            if (cnt == m + 1){
                for(int i = 1; i <= n; i++){
                    cout << ans[i]<<' ';
                }
                exit(0);
            }
        }
        return ;
    }
    for(int i = 1; i <= n; i++){
        // 第一轮只从初始排列开始
        if (f == 0)
        {
            i = t[cur];
        }
        if(vis[i] == 0){
            vis[i] = 1;
            ans[cur] = i;
            dfs(cur + 1);   
            vis[i] = 0; 
        }
    }
    return ;
}

int main(){
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    cin >> n >> m;
    // 读入初始排列
    for(int i = 1; i <= n; i++) cin >> t[i];
    dfs(1);
    return 0;
}

重点二

重新复习了广搜,并给予了一套模板。与以往相比,合法性判断被独立为函数,并提供一种新思路:使用二维数组记录ta的上一个位置。这在做广搜路径问题中显得尤为方便。 代码(D4231迷宫问题):

#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
struct P{
    int x, y;
};
P pre[100][100];
int n, m, dis[100][100];
char c[100][100];
bool vis[100][100];
int dy[] = {-1, 0, 1, 0};
int dx[] = {0, 1, 0, -1}; 
bool check(int x, int y){
    return (x >= 1 && x <= n && y >= 1 && y <= m && vis[x][y] == 0 && c[x][y] == '0');
}
void print(int x, int y){
    if(pre[x][y].x == 0 && pre[x][y].y == 0){
        return ;
    }
    print(pre[x][y].x, pre[x][y].y);
    cout << "(" << pre[x][y].x - 1<< ", " << pre[x][y].y - 1<< ")"<<endl;
}

void bfs(){
queue<P> q;
    q.push({1, 1});
    vis[1][1] = 1;
    dis[1][1] = 0;
    while(!q.empty()){
        P t = q.front();
        q.pop();
        for(int i = 0; i < 4; i++){
            int xx = t.x + dx[i];
            int yy = t.y + dy[i];
            if(check(xx, yy)){
//              cout << xx << ' ' << yy << endl;
                dis[xx][yy] = dis[t.x][t.y] + 1;
                pre[xx][yy] = {t.x, t.y};
                vis[xx][yy] = 1;
                q.push({xx, yy});
                if(xx == n && yy == m){
                    print(xx, yy);
                    cout << "(" << n - 1 << ", " << m - 1 << ")";
                    return ;
                }
            }
        }
    } 
    return ;
}
int main(){
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    n = 5; m = 5;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            cin >> c[i][j];
        } 
    }
    bfs();
    return 0;
}

好了,今天的总结就到此结束,感谢您的观看!😊😊😊