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;
}

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

相关推荐
ShineWinsu4 分钟前
对于Qt:QProgressBar常见属性的解析
开发语言·c++·qt·进度条·gui·定时器·qprogressbar
努力努力再努力wz9 分钟前
【Lua 入门系列】Lua数据结构:从 Table 出发,一文串联数组、链表、栈、队列、集合、映射与树的实现原理
数据结构·链表·lua
ShineWinsu15 分钟前
对于Qt:QLCDNumber常见属性以及QTimer的解析
服务器·数据库·c++·qt·gui·qtimer·qlcdnumber
xiaoye-duck23 分钟前
《C++ 工具库实战》C++ 解析利器 JsonCpp:从基础使用到封装简易 JSON 工具
c++·json·第三方库
dialect_9 小时前
KMP算法
开发语言·c++·算法
reikocao9 小时前
卡尔曼滤波的动态机制:P如何改变融合权重
算法
漂流瓶jz9 小时前
UVA-1612 猜名次 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·排序·aoapc·算法竞赛入门经典
吞下星星的少年·-·10 小时前
Div.2 CF 1130B题(构造,贪心)
算法·贪心·构造
ShineWinsu11 小时前
对于Qt:QRadioButton常见属性以及QButtonGroup的解析
数据库·c++·qt·microsoft·gui·qradiobutton·qbuttongroup
傲世仙尊11 小时前
多态-虚表才活到运行期符号表早已消失
c++