【洛谷 P1002】[NOIP2002 普及组] 过河卒 题解(递归+记忆化搜索)-CSDN博客

122 阅读2分钟

[NOIP2002 普及组] 过河卒

题目描述

棋盘上 A A A 点有一个过河卒,需要走到目标 B B B 点。卒行走的规则:可以向下、或者向右。同时在棋盘上 C C C 点有一个对方的马,该马所在的点和所有跳跃一步可达的点称为对方马的控制点。因此称之为“马拦过河卒”。

棋盘用坐标表示, A A A 点 ( 0 , 0 ) (0, 0) (0,0)、 B B B 点 ( n , m ) (n, m) (n,m),同样马的位置坐标是需要给出的。

现在要求你计算出卒从 A A A 点能够到达 B B B 点的路径的条数,假设马的位置是固定不动的,并不是卒走一步马走一步。

输入格式

一行四个正整数,分别表示 B B B 点坐标和马的坐标。

输出格式

一个整数,表示所有的路径条数。

样例 #1

样例输入 #1

6 6 3 3

样例输出 #1

6

提示

对于 100 % 100 \% 100% 的数据, 1 ≤ n , m ≤ 20 1 \le n, m \le 20 1≤n,m≤20, 0 ≤ 0 \le 0≤ 马的坐标 ≤ 20 \le 20 ≤20。

【题目来源】

NOIP 2002 普及组第四题

思路

该点路径数等于该点左边点的路径数与该点上面点的路径数之和。
从终点一直推回到起点,注意不要越界。数据会很大,记得用long long。

AC代码

#include <iostream>
#include <vector>
#define AUTHOR "HEX9CF"
using namespace std;

long long f(long long x, long long y);
long long n, m, c1, c2;
int ctrl[9][2] = {0, 0, 2, 1, 1, 2, -2, -1, -1, -2, -2, 1, -1, 2, 2, -1, 1, -2};
vector<vector<long long>> mem(30, vector<long long>(30, -1));
long long count = 0;

int main()
{
    cin >> n >> m >> c1 >> c2;

    /* for (long long i = 0; i < 9; i++)
    {
        cout << ctrl[i][1] << "," << ctrl[i][2] << endl;
    } */

    cout << f(n, m) << endl;
    // cout << count << endl;

    return 0;
}

long long f(long long x, long long y)
{
    if (mem[x][y] != -1)
    {
        return mem[x][y];
    }

    for (long long i = 0; i < 9; i++)
    {
        if (ctrl[i][0] + c1 == x && ctrl[i][1] + c2 == y)
        {
            // cout << ctrl[i][1] << "," << ctrl[i][2] << endl;
            // cout << 1 << endl;
            mem[x][y] = 0;
            return 0;
        }
    }

    if (x == 0 && y == 0)
    {
        count++;
        mem[x][y] = 1;
        return 1;
    }
    else if (x == 0)
    {
        mem[x][y] = f(x, y - 1);
        return mem[x][y];
    }
    else if (y == 0)
    {
        mem[x][y] = f(x - 1, y);
        return mem[x][y];
    }
    else
    {
        mem[x][y] = f(x - 1, y) + f(x, y - 1);
        return mem[x][y];
    }
    return mem[x][y];
}