码迷,mamicode.com
首页 > 其他好文 > 详细

线段树(模板

时间:2019-08-24 10:01:06      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:typedef   ==   +=   模板   date   with   main   get   oid   

某大佬的模板

#include <iostream> #include <cstdio> typedef long long LL; LL n, a[100005], d[270000], b[270000]; void build(LL l, LL r, LL p) {//建树 if (l == r) { d[p] = a[l]; return; } LL m = (l + r) >> 1; build(l, m, p << 1), build(m + 1, r, (p << 1) | 1); d[p] = d[p << 1] + d[(p << 1) | 1]; } void update(LL l, LL r, LL c, LL s, LL t, LL p) {//区间加数 if (l <= s && t <= r) { d[p] += (t - s + 1) * c, b[p] += c; return; } LL m = (s + t) >> 1; if (b[p]) d[p << 1] += b[p] * (m - s + 1), d[(p << 1) | 1] += b[p] * (t - m), b[p << 1] += b[p], b[(p << 1) | 1] += b[p]; b[p] = 0; if (l <= m) update(l, r, c, s, m, p << 1); if (r > m) update(l, r, c, m + 1, t, (p << 1) | 1); d[p] = d[p << 1] + d[(p << 1) | 1]; } LL getsum(LL l, LL r, LL s, LL t, LL p) {//区间查询 if (l <= s && t <= r) return d[p]; LL m = (s + t) >> 1; if (b[p]) d[p << 1] += b[p] * (m - s + 1), d[(p << 1) | 1] += b[p] * (t - m), b[p << 1] += b[p], b[(p << 1) | 1] += b[p]; b[p] = 0; LL sum = 0; if (l <= m) sum = getsum(l, r, s, m, p << 1); if (r > m) sum += getsum(l, r, m + 1, t, (p << 1) | 1); return sum; } int main() { std::ios::sync_with_stdio(0); LL q, i1, i2, i3, i4; std::cin >> n >> q; for (LL i = 1; i <= n; i++) std::cin >> a[i]; build(1, n, 1); while (q--) { std::cin >> i1 >> i2 >> i3; if (i1 == 2) std::cout << getsum(i2, i3, 1, n, 1) << "\n"; else std::cin >> i4, update(i2, i3, i4, 1, n, 1); } return 0; }

  

线段树(模板

标签:typedef   ==   +=   模板   date   with   main   get   oid   

原文地址:https://www.cnblogs.com/liuxiangyu666/p/11403528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!