AcWing
797. 差分
#include <bits/stdc++.h>
using namespace std;
int n, m;
const int N = 100010, M = 100010;
int a[N], b[N];
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> a[i];
b[i] = a[i] - a[i - 1];
}
while(m --){
int l, r, c;
cin >> l >> r >> c;
b[l] += c;
b[r + 1] -= c;
}
int sum = 0;
for(int i = 1; i <= n; i++){
sum += b[i];
cout << sum << ' ';
}
return 0;
}
仅使用一个数组:
#include <bits/stdc++.h>
using namespace std;
int n, m;
const int N = 100010, M = 100010;
int b[N];
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> b[i];
for(int i = n; i; i --) b[i] = b[i] - b[i - 1];
while(m --){
int l, r, c;
cin >> l >> r >> c;
b[l] += c;
b[r + 1] -= c;
}
int sum = 0;
for(int i = 1; i <= n; i++){
sum += b[i];
cout << sum << ' ';
}
return 0;
}