差分
给定一个序列
证明
性质
把序列
修改操作复杂度从
语文成绩
题目背景
语文考试结束了,成绩还是一如既往地有问题。
题目描述
语文老师总是写错成绩,所以当她修改成绩的时候,总是累得不行。她总是要一遍遍地给某些同学增加分数,又要注意最低分是多少。你能帮帮她吗?
输入格式
第一行有两个整数
第二行有
接下来
输出格式
输出仅一行,代表更改分数后,全班的最低分。
样例 #1
样例输入 #1
3 2
1 1 1
1 2 1
2 3 1样例输出 #1
2提示
对于
对于
对于
对于
题解
c++
#include <bits/stdc++.h>
using namespace std;
const int N = 5e6 + 5;
int a[N], b[N], n, p, x, y, k;
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];
b[i] = a[i] - a[i - 1]; // 差分数组
}
int ans = 1e9;
while (p--) {
cin >> x >> y >> k;
b[x] += k; // 差分将区间操作转化为两点操作
b[y + 1] -= k;
}
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1] + b[i]; // 利用前缀和还原数组
ans = min(ans, a[i]);
}
cout << ans << endl;
return 0;
}二维差分
对于原序列
修改操作:对矩阵
还原数组利用前缀和
地毯
题目描述
在
给出这些地毯的信息,问每个点被多少个地毯覆盖。
输入格式
第一行,两个正整数
接下来
输出格式
输出
第
样例 #1
样例输入 #1
5 3
2 2 3 3
3 3 5 5
1 2 1 4样例输出 #1
0 1 1 1 0
0 1 1 0 0
0 1 2 1 1
0 0 1 1 1
0 0 1 1 1提示
样例解释
覆盖第一个地毯后:
覆盖第一、二个地毯后:
覆盖所有地毯后:
数据范围
对于
对于
题解
c++
#include <iostream>
#include <vector>
using namespace std;
using i64 = long long;
void solve() {
int n, m, q;
cin >> n >> m >> q;
vector<vector<i64>> a(n + 2, vector<i64>(m + 2));
vector<vector<i64>> diff(n + 2, vector<i64>(m + 2));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
diff[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1];
}
}
while (q--) {
int x1, x2, y1, y2, k;
cin >> x1 >> y1 >> x2 >> y2 >> k;
diff[x1][y1] += k;
diff[x1][y2 + 1] -= k;
diff[x2 + 1][y1] -= k;
diff[x2 + 1][y2 + 1] += k;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
diff[i][j] += diff[i][j - 1] + diff[i - 1][j] - diff[i - 1][j - 1];
cout << diff[i][j] << " ";
}
cout << "\n";
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
// cin >> _;
while (_--) {
solve();
}
return 0;
}