A Simple Problem with Integers
Description You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval. Input The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000. Output You need to answer all Q commands in order. One answer in a line. Sample Input 10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4 Sample Output 4 55 9 15 Hint
The sums may exceed the range of 32-bit integers.
Source
POJ Monthly--2007.11.25, Yang Yi
|
想要写点什么,又不知怎么写。(ps:刚刚入门)
(蓝桥,省赛,天梯。。。一堆的比赛就要将自己的小身板压垮了,坚持!想想两个月后就要加入了程序猿的队伍,期待又胆怯。
越努力,越幸运---致默默为祖国IT事业做出自己贡献的网络搬运工)
#include <cstdio> #include <cstring> #include <iostream> using namespace std; typedef long long LL; #define Lson 2 * o, L, M //左儿子 宏定义 会有意想不到的好处 #define Rson 2 * o + 1, M + 1, R //右儿子 #define lo 2 * o #define ro 2 * o + 1 const int maxn = 4 * 100000 + 10; int ql, qr, v; long long sum[maxn], add[maxn]; //向上传递,由 o 的左右子树更新 o void pushUp(int o) { sum[o] = sum[lo] + sum[ro]; } //向下传递,维护节点o void pushDown(int o, int m) { if (add[o]) //本节点有标记才传递 { add[lo] += add[o]; //左子树点增加 add[ro] += add[o]; //右子树点增加 sum[lo] += add[o] * (m - (m / 2)); //左子树区间段增加 sum[ro] += add[o] * (m / 2); //右子树区间段增加 add[o] = 0; //清除本节点标记 } } //建树 void Build(int o, int L, int R) { add[o] = 0; //建树时初始节点都未标记 if (L == R) scanf("%lld", &sum[o]); //叶子节点 else { int M = (L + R) / 2; Build(Lson); //建立左子树 Build(Rson); //建立右子树 pushUp(o); //更新本节点 } } //更新区间 [ql,qr] 内的值加上 v void Update(int o, int L, int R) { if (ql <= L && qr >= R) //递归边界 { add[o] += v; //累加边界的add值 sum[o] += v * (R - L + 1); //计算区间和 } else { pushDown(o, R - L + 1); int M = (L + R) / 2; if (ql <= M) Update(Lson); //先递归更新左子树或者右子树 if (qr > M) Update(Rson); pushUp(o); //更新本节点 } } //查询区间[ql,qr] 的和 LL Query(int o, int L, int R) { if (ql <= L && qr >= R) //递归边界 { return sum[o]; } else { pushDown(o, R - L + 1); //用边界区间的附加信息更新答案 int M = (L + R) / 2; LL ans = 0; //递归统计,累加参数add if (ql <= M) ans += Query(Lson); if (qr > M) ans += Query(Rson); return ans; } } int main() { int n, q; while (~scanf("%d%d", &n, &q)) { Build(1, 1, n); char ch[5]; for (int i = 1; i <= q; i++) { scanf("%s", ch); if (ch[0] == 'Q') { scanf("%d%d", &ql, &qr); printf("%lld\n", Query(1, 1, n)); } else { scanf("%d%d%d", &ql, &qr, &v); Update(1, 1, n); } } } return 0; }