Such topics would be the first model to build up, pick a good state to make a lot of dp simplified equation
/ * DP [I] [0] represents the right to left, and finally stopped at the left end dp [i] [1] represents a left to right, the last stop in the right dp [i + 1] [0 ] = min (dis ( Lpre-> Ri of +. 1) + DP [pre] [0], DIS (Rpre-> Ri of +. 1) + DP [pre] [. 1]) of Li + Ri of + +. 1. 1- DP [I +. 1] [. 1 ] = min (DIS (Lpre-> of Li +. 1) + DP [pre] [0], DIS (Rpre-> of Li +. 1) + DP [pre] [. 1]) + of Li-Ri of + +. 1. 1; * / #include <bits / STDC ++ H.> the using namespace STD; #define LL Long Long #define N 200005 #define INF 0x3f3f3f3f3f3f3f3f LL n-, m, K, Q, B [N], L [N], R & lt [N] , DP [N] [ 2 ]; Long Long DIS (LL POS1, POS2 LL) { // pos1-> POS2 cost IF (POS1> POS2) the swap (POS1, POS2); int T = lower_bound (B +. 1 , B + . 1 + Q, pos1) - B; IF ! (T = Q + . 1 && B [T] <= POS2) return POS2-pos1; // There sandwich LL RES = INF; // find the left pos1 the IF (T =! . 1 ) { T - ; RES = min (RES, 2 * (POS1-B [T]) + pos2- POS1); } T = lower_bound (B + . 1 , B + . 1 + Q, POS2) - B; IF (! = T + Q . 1 ) RES = min (RES, 2*(b[t]-pos2)+pos2-pos1); return res; } int main(){ memset(L,0x3f,sizeof L); memset(R,0,sizeof R); L[1]=R[1]=1; cin>>n>>m>>k>>q; for(int i=1;i<=k;i++){ ll r,c;cin>>r>>c; L[r]=min(L[r],c); R[r]=max(R[r],c); } for(int I = . 1 ; I <= Q; I ++) CIN >> B [I]; Sort (B + . 1 , B + . 1 + Q); Memset (DP, 0x3F , the sizeof DP); // preprocessing a first row if (R & lt [ . 1 !] = . 1 ) DP [ . 1 ] [ . 1 ] R & lt = [ . 1 ] - . 1 ; // if the first line has (1,1) beyond a point, it must be stopped at the right end of the else DP [ . 1 ] [ . 1 ] DP = [ . 1 ] [ 0 ] = 0 ; // point (1,1) or no points, then stopped at the expense of both left and right ends 0 int pre=1; for(int i=2;i<=n;i++)if(R[i]){ dp[i][0]=min(dis(L[pre],R[i])+dp[pre][0] , dis(R[pre],R[i])+dp[pre][1])+R[i]-L[i];//右到左 dp[i][1]=min(dis(L[pre],L[i])+dp[pre][0] , dis(R[pre],L[i])+dp[pre][1])+R[i]-L[i];//左到右 pre=i; } cout<<min(dp[pre][0],dp[pre][1])+pre-1<<'\n'; }