D - Back and Forth Distance 解説 by en_translator 印刷ページ
By symmetry, it is sufficient to consider queries with \(s < t\).
We divide into cases depending on the first move.
If the destination of the first move has an index greater than \(s\), the cost of the first move is \(R_s\), so the total cost is at least \(R_s\). But directly moving from cell \(s\) to cell \(t\) in one move indeed achieves a total cost of \(R_s\). Hence, the minimum total cost in this case is \(R_s\).
Next, suppose the destination of the first move has an index less than \(s\). Then the travel requires at least one move from a cell with an index less than \(s\) to a cell with a larger index. The cost required for the latter move is at least \(\displaystyle\min_{i < s} R_i\); together with the cost of the initial move \(L_s\), the total cost is at least \(L_s + \displaystyle\min_{i < s} R_i\). But moving to a cell \(u\) with \(\displaystyle\min_{i < s} R_i = R_u\) and \(u < s\) in the first move, and then moving to cell \(t\) in the next move, indeed incurs a total cost of \(L_s + \displaystyle\min_{i < s} R_i\). Hence, the minimum total cost in this case is \(L_s + \displaystyle\min_{i < s} R_i\).
To wrap up, the answer to a query with \(s < t\) is \(\min(R_s, L_s + \displaystyle\min_{i < s} R_i)\). By precalculating the minimum for all prefixes of \(R\), each query can be answered in \(O(1)\) time.
For a query with \(s > t\), the answer is \(\min(L_s, R_s + \displaystyle\min_{i > s}L_i)\), so it suffices to precalculate the minimum for all suffixes of \(L\).
Sample code
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
vector<int> L(n), R(n);
for (int i = 1; i < n; i++) cin >> L[i];
for (int i = 0; i < n - 1; i++) cin >> R[i];
vector<int> A = L, B = R;
for (int i = n - 2; i >= 0; i--) A[i] = min(A[i], A[i + 1]);
for (int i = 1; i < n; i++) B[i] = min(B[i], B[i - 1]);
while (q--) {
int s, t;
cin >> s >> t;
s--; t--;
if (s < t) {
int ans = R[s];
if (s > 0) ans = min(ans, L[s] + B[s - 1]);
cout << ans << '\n';
}
else {
int ans = L[s];
if (s < n - 1) ans = min(ans, R[s] + A[s + 1]);
cout << ans << '\n';
}
}
}
投稿日時:
最終更新: