區間更新+差分

荔枝在哪里發表於2024-05-31

題目連結:區間更新
程式碼


#include<iostream>
using namespace std;

const int N = 1e5 + 5;

int a[N], b[N];

int main() {
	int n, m;
	while (cin >> n >> m) {
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
			b[i] = a[i] - a[i -1];
//			cout << b[i] << " ";
		}
//		cout << endl;
		for (int i = 0; i < m; i++) {
			int x, y, z;
			cin >> x >> y >> z;
			b[x] += z;
			b[y + 1] -= z;
		}
//		for (int i = 1; i <= n; i++) {
//			cout << b[i] << " ";
//		}
//		cout << endl;
		for (int i = 1; i <= n; i++) {
			a[i] = a[i - 1] + b[i];
			cout << a[i] << ' ';
			//也可以換成b,可以看出此時用哪個陣列已經不重要了 
//			b[i] = b[i - 1] + b[i];
//			cout << b[i] << ' ';
		}
		cout << endl;
	}
	return 0;
}

相關文章