POJ 3468 A Simple Problem with Integers

来源:互联网 发布:金风科技二期淘宝地址 编辑:程序博客网 时间:2024/05/29 18:11

Description

给出了一个序列,你需要处理如下两种询问。

"C a b c"表示给[a, b]区间中的值全部增加c (-10000 ≤ c ≤ 10000)。

"Q a b" 询问[a, b]区间中所有值的和。

Input

第一行包含两个整数N, Q。1 ≤ N,Q ≤ 100000.

第二行包含n个整数,表示初始的序列A (-1000000000 ≤ Ai ≤ 1000000000)。

接下来Q行询问,格式如题目描述。

Output

对于每一个Q开头的询问,你需要输出相应的答案,每个答案一行。

Sample Input

10 51 2 3 4 5 6 7 8 9 10Q 4 4Q 1 10Q 2 4C 3 6 3Q 2 4

Sample Output

4559

15

区间更新区间求和,拿来用splay练练手

#include<cstdio>#include<cstring>#include<cmath>#include<queue>#include<vector>#include<iostream>#include<algorithm>#include<bitset>#include<functional>using namespace std;typedef unsigned long long ull;typedef long long LL;const int maxn = 1e5 + 10;int n, m, l, r, c, root, a[maxn];char s[10];struct Splays{const static int maxn = 1e5 + 10;const static int INF = 0x7FFFFFFF;int ch[maxn][2], F[maxn], U[maxn], C[maxn], A[maxn], sz, G[maxn];LL S[maxn];int Node(int f, int u, int c) { C[sz] = 1; S[sz] = A[sz] = c; G[sz] = ch[sz][0] = ch[sz][1] = 0; F[sz] = f; U[sz] = u; return sz++; }void clear(){ sz = 1; ch[0][0] = ch[0][1] = C[0] = A[0] = U[0] = F[0] = S[0] = G[0] = 0; }void Pushdown(int x){if (!G[x]) return;if (ch[x][0]) G[ch[x][0]] += G[x], S[ch[x][0]] += (LL)G[x] * C[ch[x][0]];if (ch[x][1]) G[ch[x][1]] += G[x], S[ch[x][1]] += (LL)G[x] * C[ch[x][1]];A[x] += G[x];G[x] = 0;}void rotate(int x, int k){int y = F[x]; ch[y][!k] = ch[x][k]; F[ch[x][k]] = y;if (F[y]) ch[F[y]][y == ch[F[y]][1]] = x;F[x] = F[y];    F[y] = x;ch[x][k] = y;C[x] = C[y];C[y] = C[ch[y][0]] + C[ch[y][1]] + 1;S[x] = S[y];S[y] = S[ch[y][0]] + S[ch[y][1]] + A[y];}void Splay(int x, int r){for (int fa = F[r]; F[x] != fa;){if (F[F[x]] == fa) { rotate(x, x == ch[F[x]][0]); return; }int y = x == ch[F[x]][0], z = F[x] == ch[F[F[x]]][0];y^z ? (rotate(x, y), rotate(x, z)) : (rotate(F[x], z), rotate(x, y));}}void insert(int &x, int u){for (int i = x; i; i = ch[i][U[i] < u]){Pushdown(i);if (u == U[i]){Splay(i, x); x = i; break;}}}void add(int &x, int l, int r, int c){insert(x, l - 1);insert(ch[x][1], r + 1);G[ch[ch[x][1]][0]] += c;S[ch[ch[x][1]][0]] += (LL)c*C[ch[ch[x][1]][0]];S[ch[x][1]] += (LL)c*C[ch[ch[x][1]][0]];S[x] += (LL)c*C[ch[ch[x][1]][0]];}void find(int &x, int l, int r){insert(x, l - 1);insert(ch[x][1], r + 1);printf("%lld\n", S[ch[ch[x][1]][0]]);}void build(int fa, int &x, int l, int r){if (l > r) return;if (l == r) { x = Node(fa, l, a[l]); return; }int mid = l + r >> 1;x = Node(fa, mid, a[mid]);build(x, ch[x][0], l, mid - 1);build(x, ch[x][1], mid + 1, r);C[x] += C[ch[x][0]] + C[ch[x][1]];S[x] += S[ch[x][0]] + S[ch[x][1]];}}solve;int main(){while (scanf("%d%d", &n, &m) != EOF){solve.clear();a[0] = a[n + 1] = root = 0;for (int i = 1; i <= n; i++)scanf("%d", &a[i]);solve.build(0, root, 0, n + 1);while (m--){scanf("%s", s);if (s[0] == 'Q') scanf("%d%d", &l, &r), solve.find(root, l, r);else scanf("%d%d%d", &l, &r, &c), solve.add(root, l, r, c);}}return 0;}


0 0