1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
#include <iostream> #include <cstdio> #include <queue> #include <sstream> #include <string> #include <cstring> #include <cmath> #define ll long long #define INF 500000000 using namespace std; struct point{ int left; int right; }; point arr[20005]; ll dp[20005][2]; void init() { for(int i=0;i<20005;i++) for(int j=0;j<2;j++) dp[i][j]=INF; } ll _min(ll a,ll b) { if(a<b) return a; return b; } int main() { int n; ll path; int y1,y2; while(scanf("%d",&n),n) { init(); for(int i=1;i<=n;i++) { scanf("%d%d",&y1,&y2); arr[i].left=(y1<=y2?y1:y2); arr[i].right=(y1>=y2?y1:y2); } dp[1][0]=_min(dp[1][0], (arr[1].right-1) + (arr[1].right-arr[1].left) ); dp[1][1]=_min(dp[1][1], (arr[1].right-1) ); for(int i=2;i<=n;i++) { dp[i][0] = _min( dp[i][0] , _min( dp[i-1][0] + (arr[i].right - arr[i].left) + abs(arr[i].right-arr[i-1].left), dp[i-1][1] + (arr[i].right - arr[i].left) + abs(arr[i].right-arr[i-1].right) ) )+1; dp[i][1] = _min( dp[i][1] , _min( dp[i-1][0] + (arr[i].right - arr[i].left) + abs(arr[i].left-arr[i-1].left), dp[i-1][1] + (arr[i].right - arr[i].left) + abs(arr[i].left-arr[i-1].right) ) )+1; } path = ( (dp[n][0]+n-arr[n].left) < (dp[n][1]+n-arr[n].right)? (dp[n][0]+n-arr[n].left):(dp[n][1]+n-arr[n].right)); printf("%lld\n",path); } return 0; } |