POJ3468 A Simple Problem with Integers 分块

Posted wstong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ3468 A Simple Problem with Integers 分块相关的知识,希望对你有一定的参考价值。

POJ3468 A Simple Problem with Integers

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm> 
 4 #include <cmath>
 5 using namespace std;
 6 typedef long long ll;
 7 const int maxn = 1e5+5;
 8 int L[maxn], R[maxn];  // 每个区间的范围
 9 int pos[maxn];  // 记录所属块
10 ll sum[maxn], a[maxn];
11 ll add[maxn];  // lazy标记
12 
13 void change(int l, int r, int v) {
14     int p = pos[l], q = pos[r];
15     if (p == q) {  // 如果属于同一块
16         for (int i = l; i <= r; i++) a[i] += v;
17         sum[p] += (ll)(r-l+1)*v;
18     }
19     else {
20         for (int i = p+1; i <= q-1; i++) add[i] += v;  // p和q中间的块的add 
21         for (int i = l; i <= R[p]; i++) a[i] += v;
22         sum[p] += (ll)(R[p]-l+1)*v;
23         for (int i = L[q]; i <= r; i++) a[i] += v;
24         sum[q] += (ll)(r-L[q]+1)*v;
25     }
26 }
27 ll query(int l, int r) {
28     int p = pos[l], q = pos[r];
29     ll ans = 0;
30     if (p == q) {
31         for (int i = l; i <= r; i++) ans += a[i];
32         ans += add[p]*(r-l+1);
33     }
34     else {
35         for (int i = p+1; i <= q-1; i++) ans += sum[i] + add[i]*(R[i]-L[i]+1);
36         for (int i = l; i <= R[p]; i++) ans += a[i];
37         ans += add[p]*(R[p]-l+1);
38         for (int i = L[q]; i <= r; i++) ans += a[i];
39         ans += add[q]*(r-L[q]+1);
40     }
41     return ans;
42 }
43 
44 int main() {
45     int n, q; scanf("%d%d",&n,&q);
46     for (int i = 1; i <= n; i++) scanf("%lld",&a[i]);
47     int t = sqrt(n);
48     for (int i = 1; i <= t; i++) {
49         L[i] = (i-1)*t + 1;
50         R[i] = i*t;
51     }
52     if (R[t] < n) t++, L[t] = R[t-1]+1, R[t] = n;
53     for (int i = 1; i <= t; i++) {
54         for (int j = L[i]; j <= R[i]; j++) {
55             pos[j] = i;
56             sum[i] += a[j];
57         }
58     }
59     while (q--) {
60         char cmd[10];
61         int l, r, v;
62         scanf("%s",cmd);
63         if (cmd[0] == Q) {
64             scanf("%d%d",&l,&r);
65             printf("%lld
",query(l,r));
66         }
67         else {
68             scanf("%d%d%d",&l,&r,&v);
69             change(l,r,v);
70         }
71     }
72     return 0;
73 }

 

以上是关于POJ3468 A Simple Problem with Integers 分块的主要内容,如果未能解决你的问题,请参考以下文章

A Simple Problem with Integers POJ - 3468

POJ - 3468 A Simple Problem with Integers

[poj3468]A Simple Problem with Integers

POJ3468 a simple problem with integers 分块

POJ 3468 A Simple Problem with Integers 树状数组

POJ 3468 A Simple Problem with Integers