差分

· · 算法·理论

差分(Difference Array,diff)

算法概念

差分(Difference Array)是一种通过计算原数组相邻元素之差构建的新数组,常用于优化区间更新操作的时间复杂度。其核心思想是将原数组的区间操作转化为差分数组的单点操作,通过前缀和还原原数组。 ‌

计算方法以及差分的特性

例题

P3406 海底高铁

题意

给定 n 个点和 n - 1 条铁路,每条铁路的单价 a_i ,办这条铁路的卡要 c_i​ 元,用卡支付单价是 b_i 元。

给定 m 个要去的城市,顺序: p_1,p_2,\dots,p_m 求最小花费

思路

代码

#include <bits/stdc++.h>
#define int long long //要记得开long long
using namespace std;
const int N = 1e5 + 5;
int p[N], a[N], b[N], c[N], cnt[N], diff[N];
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
        cin >> p[i];
    for (int i = 1; i < n; i++)
        cin >> a[i] >> b[i] >> c[i];
    for (int i = 1; i < m; i++) {
        int l = p[i], r = p[i + 1]; 
        if (l > r) //判断是否要交换l和r
            swap(l, r);
        diff[l]++;
        diff[r]--; //这里的r + 1 - 1直接抵消
    }
    int ans = 0;
    for (int i = 1; i < n; i++) {
        cnt[i] = cnt[i - 1] + diff[i]; //使用前缀和还原cnt数组
        ans += min(a[i] * cnt[i], c[i] + b[i] * cnt[i]); //计算是直接买票还是办卡
    }
    cout << ans;
    return 0;
}

P3078 [USACO13MAR] Poker Hands S

题意

给定 n 种牌面和Bessie手上第 i 种牌有几张,一次可以选择一张标号为 i 的牌和一张标号为 j 的牌,并打出从 i 到 j 的所有牌,要求求出最少要多少次出牌Bessie才能把她手上的牌出完。

思路

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int a[N], diff[N];
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    long long cnt1 = 0, cnt2 = 0; //开long long
    for (int i = 1; i <= n; i++) {
        diff[i] = a[i] - a[i - 1]; //计算差分数组
        if (diff[i] < 0)
            cnt1 -= diff[i]; //如果是负数,计算差
        if (diff[i] > 0)
            cnt2 += diff[i]; //如果是正数,计算和
    }
    cout << max(cnt1, cnt2); //选取其中大的那个即为答案
    return 0;
}