//洛谷p2367語文成績
一維差分
#include<iostream>
using namespace std;
const int N = 10000010;
int a[N], b[N];
int n;
int p;
void insert(int l, int r, int c) {
b[l] += c;
b[r + 1] -= c;
}
int main() {
cin >> n >> p;
for (int i = 1; i <= n; i++) {
cin >> a[i];
insert(i, i, a[i]);//初始化b陣列 a[k]=b[1]+b[2]+b[]+...+b[k]
}
while(p--){
int x, y, z;
cin >> x >> y >> z;
insert(x, y, z);
}
for (int i = 1; i <= n; i++) {
b[i] += b[i - 1];//將b陣列變成自己的字首和
}
//如果用其他陣列存s[i]=s[i-1]+a[i];
int tmp = b[1];
for (int i = 2; i <= n; i++) {
if (tmp > b[i])tmp = b[i];
}
cout << tmp;
}
//洛谷p3397地毯
二維差分
#include<iostream>
using namespace std;
const int N=10010;
int n, m;
int a[N][N], b[N][N];
void insert(int x1, int y1, int x2, int y2,int c) {
b[x1][y1] += c;
b[x2 + 1][y1] -= c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y2 + 1] += c;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
insert(i, j, i, j, a[i][j]);
}
}
while (m--) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2 ;
insert(x1, y1, x2, y2, 1);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
b[i][j] = b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1] + b[i][j];
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++) {
cout << b[i][j]<<' ';
}
cout << endl;
}
}