语文成绩
题目
题目背景
语文考试结束了,成绩还是一如既往地有问题。
题目描述
语文老师总是写错成绩,所以当她修改成绩的时候,总是累得不行。她总是要一遍遍地给某些同学增加分数,又要注意最低分是多少。你能帮帮她吗?
输入格式
第一行有两个整数 n n n, p p p,代表学生数与增加分数的次数。
第二行有 n n n 个数, a 1 ∼ a n a_1 \sim a_n a1∼an,代表各个学生的初始成绩。
接下来 p p p 行,每行有三个数, x x x, y y y, z z z,代表给第 x x x 个到第 y y y 个学生每人增加 z z z 分。
输出格式
输出仅一行,代表更改分数后,全班的最低分。
样例 #1
样例输入 #1
3 2
1 1 1
1 2 1
2 3 1
样例输出 #1
2
提示
对于 40 % 40\% 40% 的数据,有 n ≤ 1 0 3 n \le 10^3 n≤103。
对于 60 % 60\% 60% 的数据,有 n ≤ 1 0 4 n \le 10^4 n≤104。
对于 80 % 80\% 80% 的数据,有 n ≤ 1 0 5 n \le 10^5 n≤105。
对于 100 % 100\% 100% 的数据,有 n ≤ 5 × 1 0 6 n \le 5\times 10^6 n≤5×106, p ≤ n p \le n p≤n,学生初始成绩 $ \le 100 , , ,z \le 100$。
题解
本题使用了差分。
差分可以很方便地进行区间修改,它与前缀和是一种互逆的运算。
这里给出差分:
for(int i = n; i >= 1; i--)
a[i] -= a[i-1];
对于一个差分数组,一次 l 到 r 之间增加 x 的操作,只需要让 a[l] + x,a[r+1] - x即可。
最后用前缀和还原数组。、
Code:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 5e6 + 5;
const int mod = 10007;
int n, p, ans = 0x3f3f3f3f;
int a[maxn];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> p;
for(int i = 1; i <= n; i++) //输入
cin >> a[i];
for(int i = n; i >= 1; i--)//差分
a[i] -= a[i-1];
for(int i = 1; i <= p; i++) {//处理操作
int x, y, z;
cin >> x >> y >> z;
a[x] += z; a[y+1] -= z;
}
for(int i = 1; i <= n; i++) {//还原
a[i] += a[i-1];
ans = min(ans, a[i]);
}
cout << ans;
return 0;
}