社区讨论
[C] DP | Time: O(m * n), Space: O(m)
P1002[NOIP 2002 普及组] 过河卒参与者 6已保存回复 7
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 6 条
- 当前快照
- 1 份
- 快照标识符
- @mj84obry
- 此快照首次捕获于
- 2025/12/16 13:14 2 个月前
- 此快照最后确认于
- 2025/12/16 14:06 2 个月前
C
//--------kernel--------
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
static bool isReachableFromHorse(
const int horseRow,
const int horseCol,
const int targetRow,
const int targetCol
){
const int rowDiffAbs = abs(horseRow - targetRow);
const int colDiffAbs = abs(horseCol - targetCol);
return (1 == rowDiffAbs && 2 == colDiffAbs) ||
(2 == rowDiffAbs && 1 == colDiffAbs);
}
static bool isBlockedByHorse(
const int horseRow,
const int horseCol,
const int targetRow,
const int targetCol
){
return (targetRow == horseRow && targetCol == horseCol) ||
isReachableFromHorse(horseRow, horseCol, targetRow, targetCol);
}
int64_t wayCntToReachTarget(
const int horseRow,
const int horseCol,
const int targetRow,
const int targetCol
){
int64_t * dp = (int64_t *)malloc(sizeof (int64_t) * (1 + targetCol));
if (NULL == dp){
abort();
}
//init dp as first row
dp[0] = isBlockedByHorse(horseRow, horseCol, 0, 0)? 0 : 1;
for (int col = 1; col <= targetCol; col += 1){
dp[col] = isBlockedByHorse(horseRow, horseCol, 0, col)? 0 : dp[col - 1];
}
//row 1 to targetRow
for (int row = 1; row <= targetRow; row += 1){
if (isBlockedByHorse(horseRow, horseCol, row, 0)){
dp[0] = 0;
}
for (int col = 1; col <= targetCol; col += 1){
dp[col] = isBlockedByHorse(horseRow, horseCol, row, col)? 0 :
(dp[col - 1] + dp[col]);
}
}
//save result before free()
const int64_t finalWayCnt = dp[targetCol];
free(dp);
dp = NULL;
return finalWayCnt;
}
//--------main--------
#include <stdio.h>
int main(void){
int targetRow, targetCol, horseRow, horseCol;
scanf("%d%d%d%d", &targetRow, &targetCol, &horseRow, &horseCol);
const int64_t finalWayCnt = wayCntToReachTarget(horseRow, horseCol, targetRow, targetCol);
printf("%lld", finalWayCnt);
return 0;
}
回复
共 7 条回复,欢迎继续交流。
正在加载回复...