题解:P14727 [ICPC 2022 Seoul R] Frog Jump
P14727 [ICPC 2022 Seoul R] Frog Jump 题解
题意
一条直线上有
思路
如果枚举所有区间,再计算青蛙跳跃距离之和,时间复杂度为
既然不能枚举所有区间,那么我们可以记录需要跳跃的距离,因此本题的关键就在于怎么记录间断的两个相邻区间?
考虑前缀和,前缀和数组中
- 若
a_i\le maxx ,说明与前i-1 个区间有重叠端点,因此不需要跳跃,前缀和数组d_i \gets d_{i-1} 。 - 若
a_i> maxx ,说明与前i-1 个区间没有重叠端点,因此需要跳跃,跳跃距离为a_i-maxx ,前缀和数组d_i \gets a_i-maxx+d_{i-1} 。
然后更新
最后就是查询,每次访问对答案的贡献就是所在区间与上一个区间没有被线段覆盖的长度。
时间复杂度为
注意:答案可能达到 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;
}