洛谷P5019 铺设道路 题解 差分数组

题目链接:https://www.luogu.com.cn/problem/P5019

今天复习了一下差分,然后脑袋里面想题,然后就想到了这道《铺设道路》。

然后这个是我之前用 贪心 写的题解:https://www.cnblogs.com/quanjun/p/13137699.html

现在简要讲解一下差分解法:

对于数组 (d),维护一个差分数组 (c),然后我们发现每一次填都是会将一个 (c[i]) 加上 (1),将一个 (c[i]) 减去 (1)

所以最终的答案就是差分数组所有为负的元素的绝对值之和 与 所有为正的元素之和 的较大值。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n;
long long d[maxn], c[maxn], ans1, ans2;
int main() {
    cin >> n;
    for (int i = 1; i <= n; i ++) {
        cin >> d[i];
        c[i] = d[i] - d[i-1];
        if (c[i] < 0) ans1 -= c[i];
        else ans2 += c[i];
    }
    cout << max(ans1, ans2) << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/quanjun/p/13616444.html