[C++]<原创>洛谷P3842 [TJOI2007] 线段【新手向】

洛谷原题链接点这里「https://www.luogu.com.cn/problem/P3842」

其实本题不需要用列表 dp,简单写状态转移方程即可。

[TJOI2007] 线段

题目描述

在一个 n × n n \times n n×n 的平面上,在每一行中有一条线段,第 i i i 行的线段的左端点是 ( i , L i ) (i, L_{i}) (i,Li),右端点是 ( i , R i ) (i, R_{i}) (i,Ri)

你从 ( 1 , 1 ) (1,1) (1,1) 点出发,要求沿途走过所有的线段,最终到达 ( n , n ) (n,n) (n,n) 点,且所走的路程长度要尽量短。

更具体一些说,你在任何时候只能选择向下走一步(行数增加 1 1 1)、向左走一步(列数减少 1 1 1)或是向右走一步(列数增加 1 1 1)。当然,由于你不能向上行走,因此在从任何一行向下走到另一行的时候,你必须保证已经走完本行的那条线段。

输入格式

第一行有一个整数 n n n

以下 n n n 行,在第 i i i 行(总第 ( i + 1 ) (i+1) (i+1) 行)的两个整数表示 L i L_i Li R i R_i Ri

输出格式

仅包含一个整数,你选择的最短路程的长度。

样例 #1

样例输入 #1

6
2 6
3 4
1 3
1 2
3 6
4 5

样例输出 #1

24

提示

我们选择的路线是

 (1, 1) (1, 6)
 (2, 6) (2, 3)
 (3, 3) (3, 1)
 (4, 1) (4, 2)
 (5, 2) (5, 6)
 (6, 6) (6, 4) (6, 6)

不难计算得到,路程的总长度是 24 24 24

对于 100 % 100\% 100% 的数据中, n ≤ 2 × 1 0 4 n \le 2 \times 10^4 n2×104 1 ≤ L i ≤ R i ≤ n 1 \le L_i \le R_i \le n 1LiRin

My Code

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;

    int bestLeft, bestRight;
    int currentLeft, currentRight;
    int tempBestLeft;
    int previousLeft, previousRight;

    cin >> currentLeft >> currentRight;

    //第一行初始化
    bestLeft = 2 * currentRight - currentLeft - 1;
    bestRight = currentRight - 1;

    for (int i = 2; i <= n; ++i) {
        previousLeft = currentLeft;
        previousRight = currentRight;

        cin >> currentLeft >> currentRight;

        //状态转移方程
        tempBestLeft = min(abs(previousLeft - currentRight) + bestLeft,
                           abs(previousRight - currentRight) + bestRight) 
                           + currentRight - currentLeft + 1;
        bestRight = min(abs(previousLeft - currentLeft) + bestLeft,
                        abs(previousRight - currentLeft) + bestRight) 
                        + currentRight - currentLeft + 1;
        bestLeft = tempBestLeft;
    }

    cout << min(n - currentLeft + bestLeft, 
    			n - currentRight + bestRight) << endl;
    return 0;
}

思路

只要记下每行选择线段左,右分别历史最短线段长 b e s t L e f t bestLeft bestLeft b e s t R i g h t bestRight bestRight
写下状态转移方程,注意每行只和本行和上一行的线段方位 c u r r e n t current current p r e v i o u s previous previous 和上一行 b e s t L e f t bestLeft bestLeft b e s t R i g h t bestRight bestRight 相关,故不需要 dp 列表,只要记录 O ( 1 ) O(1) O(1) 数据即可。
注意初始化和最后的输出。

复杂度

时间复杂度 O ( n ) O(n) O(n)
空间复杂度 O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值