Files
exercises/dp/TJOI2007_walk_segments_dp.cpp
T
2026-09-09 13:38:11 +08:00

65 lines
1.9 KiB
C++

#include <iostream>
using namespace std;
using Segment = pair<int, int>;
constexpr int MAX_N = 20005;
int n;
Segment segments[MAX_N];
pair<int, int> dp[MAX_N]; // 从这一层的线段左/右边出去
void log_dp() {
for (int i = 0; i < n; i++) {
clog << dp[i].first << "\t" << dp[i].second << endl;
}
}
pair<int, int> get_min_steps(const Segment& segment, const int start_pos) {
const int len = segment.second - segment.first;
if (start_pos <= segment.first) {
return {segment.second - start_pos + len, segment.second - start_pos};
}
if (start_pos >= segment.second) {
return {start_pos - segment.first, start_pos - segment.first + len};
}
return {
len + (segment.second - start_pos),
len + (start_pos - segment.first)
};
}
// pair<int, int> get_min_steps(const Segment& segment, const Segment& previous_segment) {
// auto [first1, second1] = get_min_steps(segment, previous_segment.second);
// auto [first2, second2] = get_min_steps(segment, previous_segment.first);
// return {min(first1, first2), min(second1, second2)};
// }
int solve_dp() {
dp[0] = get_min_steps(segments[0], 1);
for (int i = 1; i < n; i++) {
auto [first1, second1] = get_min_steps(segments[i], segments[i - 1].first);
auto [first2, second2] = get_min_steps(segments[i], segments[i - 1].second);
first1 += dp[i - 1].first, second1 += dp[i - 1].first;
first2 += dp[i - 1].second, second2 += dp[i - 1].second;
dp[i] = {min(first1, first2), min(second1, second2)};
}
return min(dp[n - 1].first, dp[n - 1].second);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> segments[i].first >> segments[i].second;
}
segments[n] = {n, n}, n++;
cout << solve_dp() + n - 2 << endl;
log_dp();
return 0;
}