解法一:
暴力
#include<iostream>
#include<vector>
#define endl '\n'
using namespace std;
void addNum(vector<int>& a) {
int l, r, x;
cin >> l >> r >> x;
for (int i = l; i <= r; i++)
a[i] += x;
}
void minusNum(vector<int>& a) {
int l, r, x;
cin >> l >> r >> x;
for (int i = l; i <= r; i++)
a[i] -= x;
}
void print(vector<int>& a) {
int l, r;
cin >> l >> r;
for (int i = l; i <= r; i++)
cout << a[i] << " ";
cout << endl;
}
int main() {
int n, t;
cin >> n >> t;
vector<int> vec(n + 1, 0);
for (int i = 1; i <= n; i++) cin >> vec[i];
while (t--) {
int x; cin >> x;
switch (x) {
case 1: addNum(vec); break;
case 2: minusNum(vec); break;
case 3:print(vec); break;
}
}
return 0;
}
解法二:
差分
#include<iostream>
#include<vector>
#define endl '\n'
using namespace std;
void addNum(vector<int>& a) {
int l, r, x;
cin >> l >> r >> x;
a[l] += x;
a[r + 1] -= x;
}
void minusNum(vector<int>& a) {
int l, r, x;
cin >> l >> r >> x;
a[l] -= x;
a[r + 1] += x;
}
void print(vector<int>& a) {
int l, r;
cin >> l >> r;
vector<int> b(a);
for (int i = 1; i < a.size()-1; i++)
b[i] += b[i - 1];
for (int i = l; i <= r; i++)
cout << b[i] << " ";
cout << endl;
}
int main() {
int n, t;
cin >> n >> t;
vector<int> vec(n + 2, 0);
vector<int> tem(n + 2, 0);
for (int i = 1; i <= n; i++) {
cin >> tem[i];
vec[i] = tem[i] - tem[i - 1];
}
while (t--) {
int x; cin >> x;
switch (x) {
case 1: addNum(vec); break;
case 2: minusNum(vec); break;
case 3:print(vec); break;
}
}
return 0;
}