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

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

相关推荐
w陆压1 分钟前
9.野指针和悬空指针
c++·c++基础知识
shizhenshide3 分钟前
极速响应:平均破解速度<3秒的验证码服务,为抢购爬虫而生
算法
AD钙奶-lalala3 分钟前
leetcode核心母题总结
算法·leetcode·职场和发展
三月微暖寻春笋18 分钟前
【和春笋一起学C++】(五十二)关于函数返回对象时的注意事项
c++·函数·const·返回对象·返回对象的引用
努力学算法的蒟蒻19 分钟前
day53(1.4)——leetcode面试经典150
算法·leetcode·面试
leiming621 分钟前
c++ transform算法
开发语言·c++·算法
菩提祖师_25 分钟前
基于VR的虚拟会议系统设计
开发语言·javascript·c++·爬虫
裴云飞33 分钟前
Compose原理一之快照系统
算法·架构
YxVoyager33 分钟前
Qt C++ :QJson使用详解
c++·qt
橘颂TA33 分钟前
【剑斩OFFER】哈希表简介
数据结构·算法·散列表