P1002 过河卒:图论动态规划入门

本题链接:P1002 [NOIP2002 普及组] 过河卒 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

思路:

本题与之前的动态规划不一样,比如背包问题和子序列问题等都是线性dp,也就是dp数组其实主要用于存储计算的结果,而这题中的dp数组除了存储结果外,还有图的作用

  • f[ i ][ j ] 表示走到点(i,j)的路的数
  • 卒只能走右和下,因此f [ i ] [ j ] += f [ i - 1][ j] + f [ i ][ j - 1];

代码:

ac代码:

cpp 复制代码
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

int n,m,a,b;//(m,n)是目标点,(a,b)是马
//马的路
int dx[8] = {-1,-2,-2,-1,1,2,2,1};
int dy[8] = {-2,-1,1,2,-2,-1,1,2};
const int N = 30;
int limit[N][N];
long long f[N][N];


int main(){
   cin >> n >> m >> a >> b;
    limit[a][b] = true;
    for(int i = 0;i < 8;i++){
        limit[a + dx[i]][b + dy[i]] = true;
    }
    
    f[0][0] = 1;
    for(int i = 0;i <= n;i++){
        for(int j = 0;j <= m;j++){
            if(!limit[i][j]){
                if(i) f[i][j] += f[i-1][j];
                if(j) f[i][j] += f[i][j-1];
            }
        }
    }
    
    cout << f[n][m];
    
    return 0;
}

在贴一个dfs的代码,过了40/100,其他的超时了

cpp 复制代码
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

int n,m,a,b;//(m,n)是目标点,(a,b)是马
//马的路
int dx[8] = {-1,-2,-2,-1,1,2,2,1};
int dy[8] = {-2,-1,1,2,-2,-1,1,2};
const int N = 22;
int mp[N][N];
int limit[N][N];
int res = 0;
int dn[2] = {1,0};
int dm[2] = {0,1};

int charge(int x,int y){
    if(x < 0 || x > n || y < 0 || y > m) return false;
    return true;
}

void dfs(int x,int y){
    if(x == n && y == m){
        res ++;
        return;
    }
    
    for(int i = 0;i < 2;i++){
        int nowx = x + dn[i],nowy = y + dm[i];
        if(charge(nowx,nowy) && !limit[nowx][nowy]){
            dfs(nowx,nowy);
        }
    }
}

int main(){
   cin >> n >> m >> a >> b;
    limit[a][b] = true;
    for(int i = 0;i < 8;i++){
        limit[a + dx[i]][b + dy[i]] = true;
    }
    
    dfs(0,0);
    
    cout << res;
    
    return 0;
}

以上是本文全部内容,如果对你有帮助点个赞再走吧~ ₍˄·͈༝·͈˄*₎◞ ̑̑

相关推荐
unityのkiven15 分钟前
C++中析构函数不设为virtual导致内存泄漏示例
开发语言·c++
学习中的码虫19 分钟前
数据结构基础排序算法
数据结构·算法·排序算法
_安晓37 分钟前
数据结构 -- 顺序查找和折半查找
数据结构
小破农1 小时前
C++篇——多态
开发语言·c++
yidaqiqi1 小时前
[目标检测] YOLO系列算法讲解
算法·yolo·目标检测
飞天狗1111 小时前
2024 山东省ccpc省赛
c++·算法
代码不停1 小时前
Java二叉树题目练习
java·开发语言·数据结构
卡尔曼的BD SLAMer1 小时前
计算机视觉与深度学习 | Python实现EMD-SSA-VMD-LSTM-Attention时间序列预测(完整源码和数据)
python·深度学习·算法·cnn·lstm
愚润求学2 小时前
【Linux】进程间通信(一):认识管道
linux·运维·服务器·开发语言·c++·笔记
珊瑚里的鱼2 小时前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl