a591中等障礙網格的單調路徑計數
CPE:Little Red Riding Hood (UVa 11067)
用到達點的最後一步推導安全路徑數。
解題思路
令 dp[y][x] 是從 (0,0) 到 (x,y) 的安全路徑數。非狼點的最後一步只能來自 (x−1,y) 或 (x,y−1),兩種情況互斥且完備,所以將兩者相加;狼點則強制為 0。起點初始化為 1,按 y、x 遞增處理即可。
網格交叉點包含兩側端點,因此尺寸是 (h+1)×(w+1)。使用一列滾動陣列,更新前 dp[x] 代表下方,更新後 dp[x−1] 代表左方。讀到 0 0 結束;答案 0、1、多條各有不同完整英文句型。中間值可能超過最終答案,因此程式將計數飽和於 2^32,仍能保留題目保證範圍內的最終值。
Step-by-step animation
示意:w=h=2,狼在 (1,1)
步驟 1 / 3
底列
起點一路向右,各點只有一條路徑。
1
1
1
- y
- 0
- dp
- 1,1,1
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int w, h;
while (cin >> w >> h && (w || h)) {
int n;
cin >> n;
vector<vector<bool>> wolf(h + 1, vector<bool>(w + 1));
while (n--) {
int x, y;
cin >> x >> y;
wolf[y][x] = true;
}
vector<long long> dp(w + 1);
dp[0] = 1;
for (int y = 0; y <= h; ++y)
for (int x = 0; x <= w; ++x) {
if (wolf[y][x])
dp[x] = 0;
else if (x)
dp[x] = min(1LL << 32, dp[x] + dp[x - 1]);
}
long long a = dp[w];
if (!a)
cout << "There is no path.\n";
else if (a == 1)
cout << "There is one path from Little Red Riding Hood's house to her "
"grandmother's house.\n";
else
cout << "There are " << a
<< " paths from Little Red Riding Hood's house to her grandmother's "
"house.\n";
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。