noip2002 过河卒 (动态规划求路径总数)

题目描述

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

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

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

输入格式

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

输出格式

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

输入输出样例

输入

6 6 3 3

输出 

6

说明/提示

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

题目地址: 洛谷1002
 

解法1:动态规划

dp[i,j] 代表走到位置(i, j)的方案有多少种

dp[0, 0] = 1
dp[i, j] = dp[i, j - 1] + dp[i, j - 1]
#include<cstdio>
#include<algorithm>
using namespace std;

long long f[20+5][20+5];
int n, m, horse_x, horse_y; 

bool ok(int x, int y) {
	if (x > n || y > m) return 0;
	if (x == horse_x && y == horse_y) return 0; 
	if (abs(horse_x - x) == 1 && abs(horse_y - y) == 2) return 0;
	if (abs(horse_x - x) == 2 && abs(horse_y - y) == 1) return 0;
	return 1;
}

int main() {
	scanf("%d%d%d%d", &n, &m, &horse_x, &horse_y);
	f[0][0] = 1;
	for(int i = 0; i <= n; i++)
		for (int j = 0; j <= m; j++) {
			if (ok(i, j)) {
				if (j) f[i][j] += f[i][j - 1];
				if (i) f[i][j] += f[i - 1][j];
			}
		}
	printf("%I64d\n",f[n][m]);   
	return 0;
}

解法2:动态规划

在解法1的基础上,优化空间效率

dp[0] = 1

dp[i] = dp[i] + dp[i - 1]

#include<cstdio>
#include<algorithm>
using namespace std;

long long f[20+5];
int n, m, horse_x, horse_y; 

bool ok(int x, int y) {
	if (x < 0 || x > n || y < 0 || y > m) return 0;
	if (x == horse_x && y == horse_y) return 0; 
	if (abs(horse_x - x) == 1 && abs(horse_y - y) == 2) return 0;
	if (abs(horse_x - x) == 2 && abs(horse_y - y) == 1) return 0;
	return 1;
}

int main() {
	scanf("%d%d%d%d", &n, &m, &horse_x, &horse_y);
	f[0] = 1;
	for (int i = 0; i <= n; i++) {
		for (int j = 0; j <= m; j++) {
			if (!ok(i, j)) {
				f[j] = 0;	
				continue;
			}
			if(j) f[j] += f[j - 1];
		}
	}
	printf("%I64d\n",f[m]);   
	return 0;
}

解法三:矩阵乘法、直接数学排列公式计算

https://www.luogu.com.cn/blog/yummy-loves-114514/solution-p1002

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值