天天看點

COGS 2632. [HZOI 2016] 數列操作d

題目連結:​​傳送門​​ 區間加等差數列

網上沒怎麼見有解釋的

把等差數列看成一個三角形

mid從中間切開後

左兒子加的還是一個三角形

右兒子加的是一個梯形

其實也不能說是三角形

因為怎麼樣都會有一個首項在

也就是底下有一個小正方形

也就是這個樣子↓

維護這個面積

(上底+下底)*高 / 2

COGS 2632. [HZOI 2016] 數列操作d

這樣維護區間和就好了

這裡的首項和公差是當做懶标記下放的

下放給右兒子的時候要注意首項是變的

如圖(好像有點歪

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <complex>
#include <algorithm>
#include <climits>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define
#define

using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
struct node {
  int l, r; int w, a, d;
}tree[A];
void build(int k, int l, int r) {
  tree[k].l = l; tree[k].r = r;
  if (l == r) {
    tree[k].w = tree[k].a = tree[k].d = 0;
    return;
  }
  int m = (l + r) >> 1;
  build(k << 1, l, m);
  build(k << 1 | 1, m + 1, r);
}
void add(int k, int l, int r, int a, int d) {
  tree[k].a = (tree[k].a + a) % mod;
  tree[k].d = (tree[k].d + d) % mod;
  tree[k].w = (tree[k].w + (2LL * a + (r - l) * d) * (r - l + 1) / 2 % mod) % mod;
}
void down(int k) {
  int m = (tree[k].l + tree[k].r) >> 1;
  add(k << 1, tree[k].l, m, tree[k].a, tree[k].d);
  add(k << 1 | 1, m + 1, tree[k].r, (tree[k].a + tree[k].d * 1LL * (m - tree[k].l + 1) % mod) % mod, tree[k].d);
  tree[k].a = tree[k].d = 0;
}
void change(int k, int l, int r, int d) {
  if (tree[k].l >= l and tree[k].r <= r) {
    add(k, tree[k].l, tree[k].r, 1LL * (tree[k].l - l) * d % mod, d);
    return;
  }
  if (tree[k].d) down(k);
  int m = (tree[k].l + tree[k].r) >> 1;
  if (l <= m) change(k << 1, l, r, d);
  if (r > m) change(k << 1 | 1, l, r, d);
  tree[k].w = (tree[k << 1].w + tree[k << 1 | 1].w) % mod;
}
int ask(int k, int l, int r) {
  if (tree[k].l >= l and tree[k].r <= r) return tree[k].w;
  if (tree[k].d) down(k);
  int m = (tree[k].l + tree[k].r) >> 1; int ans = 0;
  if (l <= m) ans = (ans + ask(k << 1, l, r)) % mod;
  if (r > m) ans = (ans + ask(k << 1 | 1, l, r)) % mod;
  return ans;
}
int n, m, opt, a, b; int c;

int main(int argc, char const *argv[]) {
  freopen("segment.in", "r", stdin); freopen("segment.out", "w", stdout);
  scanf("%d%d", &n, &m); build(1, 1, n);
  for (int i = 1; i <= m; i++) {
    scanf("%d", &opt);
    if (!opt) {
      scanf("%d%d", &a, &b);
      printf("%d\n", ask(1, a, b));
    }
    else {
      scanf("%d%d%d", &a, &b, &c);
      change(1, a, b, c);
    }
  }
  fclose(stdin); fclose(stdout);
  return 0;
}