公式
E - Hungry Takahashi 解説 by en_translator
The following fact is important.
- If he visits cell \((i,j)\) during the tour, then it is always on Day \((i+j-1)\) that he collects coins and buy food on cell \((i,j)\).
This holds because every move increases \((i+j)\) exactly by one.
Thus, by defining \(B_{i,j}=A_{i,j}-P_{i+j-1}\), the problem can be rephrased as follows.
- When you visit cell \((i,j)\), you obtain \(B_{i,j}\) yen. (If \(B_{i,j}<0\), you lose \(-B_{i,j}\) yen.) You want to travel from \((1,1)\) to \((N,N\)) by repeating moving down or right. How much money should you initially have?
Define a DP (Dynamic Programming) as follows:
- \(\mathrm{dp}_{i,j}:\) the minimum amount of initial money (the amount before you obtain \(B_{i,j}\) yen at cell \((i,j)\)) required to travel from cell \((i,j)\) to \((H,W)\) without making the amount of money negative
This DP can be evaluated in descending order of \(i\) and \(j\). Specifically, the transitions are as follows:
- \(\mathrm{dp}_{H,W}=\max\{0,-B_{H,W}\}\)
- \(\mathrm{dp}_{i,j}= \max\{0,\min\{\mathrm{dp}_{i+1,j},\mathrm{dp}_{i,j+1}\}-B_{i,j}\}\quad((i,j) \neq (H,W))\)
For convenience, we define \(\mathrm{dp}_{i,j}=\infty\) for \(i>H\) and \(j>W\).
The time complexity is \(O(HW)\).
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int h, w;
cin >> h >> w;
vector a(h, vector<int>(w));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> a[i][j];
}
}
vector<int> p(h + w - 1);
for (int &i: p) cin >> i;
vector dp(h, vector<ll>(w, 1e18));
dp[h - 1][w - 1] = 0;
for (int i = h - 1; i >= 0; i--) {
for (int j = w - 1; j >= 0; j--) {
if (i + 1 < h) dp[i][j] = min(dp[i][j], dp[i + 1][j]);
if (j + 1 < w) dp[i][j] = min(dp[i][j], dp[i][j + 1]);
dp[i][j] += p[i + j] - a[i][j];
dp[i][j] = max(dp[i][j], 0LL);
}
}
cout << dp[0][0] << endl;
}
投稿日時:
最終更新: