栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

树状数组(c++版)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

树状数组(c++版)

树状数组模板(具体原理及说明见文末)

void update(vector& a, int pos, int k) { //更新数组
	while (pos <= n) {
		a[pos] += k;
		pos += lowbit(pos);
	}
}

int getsum(vector &a, int pos) { // 得到从1加到pos的和
	int ans = 0;
	while (pos > 0) {
		ans += a[pos];
		pos -= lowbit(pos);
	}
	return ans;
}

例题:洛谷p3373

#include

#include

using namespace std;
typedef long long ll;

ll n, m;

inline ll lowbit(ll x) {
	return x&(-x);
}

inline void update(vector& a, ll pos, ll k) {
	while (pos <= n) {
		a[pos] += k;
		pos += lowbit(pos);
	}
}

inline ll getsum(vector &a, ll pos) {
	ll ans = 0;
	while (pos > 0) {
		ans += a[pos];
		pos -= lowbit(pos);
	}
	return ans;
}

int main() {
	cin.sync_with_stdio(0);
	
	cin >> n >> m;
	vector a(n+1);
	vector tr1(n + 2), tr2(n + 2);
	for (ll i = 1; i <= n; i++) {
		cin >> a[i];
		update(tr1, i, a[i] - a[i - 1]);
		update(tr2, i, (a[i] - a[i - 1]) * (i - 1));
		
	}
	for (ll i = 0; i < m; i++) {
		ll op;
		cin >> op;
		if (op == 1) {
			ll x, y, k;
			cin >> x >> y >> k;
			update(tr1, x, k);
			update(tr1, y+1, -k);
		
			update(tr2, x, k*(x-1));
			update(tr2, y + 1, -k*y);
		}
		else {
			ll x, y;
			cin >> x >> y;
			ll ans = 0;
			
			cout << y * getsum(tr1,y) - getsum(tr2,y) - ((x - 1) * getsum(tr1, x - 1 ) - getsum(tr2, x - 1)) << endl;
		
		}
	}
}

参考了一下两篇文章,原理讲得很详细,我这里只是在将其转换为了c++代码。
洛谷p3372
cnblogs

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号