题解:P14727 [ICPC 2022 Seoul R] Frog Jump

· · 题解

P14727 [ICPC 2022 Seoul R] Frog Jump 题解

题意

一条直线上有 n 条线段,求青蛙跳跃的 k 个区间没被线段覆盖的总长度。

思路

如果枚举所有区间,再计算青蛙跳跃距离之和,时间复杂度为 O(n^2k),显然会超时。

既然不能枚举所有区间,那么我们可以记录需要跳跃的距离,因此本题的关键就在于怎么记录间断的两个相邻区间?

考虑前缀和,前缀和数组中 d_i 表示从区间 1 到区间 i 需要跳跃的距离,maxx 表示前 i-1 个区间能覆盖到的最右端点。

然后更新 maxx 为 maxx 和 b_i 的最大值即可。

最后就是查询,每次访问对答案的贡献就是所在区间与上一个区间没有被线段覆盖的长度。

时间复杂度为 O(n+k),可以通过此题。

注意:答案可能达到 10^{15},因此要开 long long。

代码

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
ll n, k, a, b, maxx, d[100005];
int main() {
    cin >> n >> k;
    for(int i = 1; i <= n; i++) {
        cin >> a >> b;
        if(i == 1) maxx = a; //起点是区间1
        if(a <= maxx) d[i] = d[i - 1]; //不需要跳跃
        else d[i] = a - maxx + d[i - 1]; //需要跳跃
        maxx = max(maxx, b);
    }
    ll x, last, ans = 0;
    while(k--) {
        cin >> x;
        ans += abs(d[x] - d[last]); //last 可能大于 x
        last = x;
    }
    cout << ans;
    return 0;
}