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.
The second line contains N numbers, the initial values
of A1, A2, ... , AN.
-1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q
lines represents an operation.
"C abc" means
adding c to each of Aa, Aa+1,
... , Ab. -10000 ≤ c ≤ 10000.
"Q ab"
means querying the sum of Aa, Aa+1,
... , Ab.
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
代码:
#include
<
stdio.h
>
#include
<
stdlib.h
>
#define
maxn 100010
struct
T
{
int
l, r;
__int64 value, delta;
}tree[
5
*
maxn];
__int64 v[maxn];
void
build(
int
l,
int
r,
int
th)
{
tree[th].l
=
l, tree[th].r
=
r, tree[th].delta
=
0
;
if
(l
==
r)
{
tree[th].value
=
v[l];
return
;
}
int
k
=
(l
+
r)
/
2
;
build(l, k, th
*
2
);
build(k
+
1
, r, th
*
2
+
1
);
tree[th].value
=
tree[th
*
2
].value
+
tree[th
*
2
+
1
].value;
}
void
update(
int
l,
int
r,
int
th, __int64 d)
{
tree[th].value
+=
(r
-
l
+
1
)
*
d;
if
(tree[th].delta)
{
tree[th].value
+=
(tree[th].r
-
tree[th].l
+
1
)
*
tree[th].delta;
//
检查更新
tree[th
*
2
].delta
+=
tree[th].delta, tree[th
*
2
+
1
].delta
+=
tree[th].delta;
//
把孩子的delta更新,即赖操作
tree[th].delta
=
0
;
}
if
(tree[th].l
==
l
&&
tree[th].r
==
r)
{
tree[th
*
2
].delta
+=
d, tree[th
*
2
+
1
].delta
+=
d;
return
;
}
int
k
=
(tree[th].l
+
tree[th].r)
/
2
;
if
(r
<=
k)
{
update(l, r, th
*
2
, d);
}
else
if
(l
>=
k
+
1
)
{
update(l, r, th
*
2
+
1
, d);
}
else
{
update(l, k, th
*
2
, d), update(k
+
1
, r, th
*
2
+
1
, d);
}
}
__int64 sum(
int
l,
int
r,
int
th)
{
if
(tree[th].delta)
{
tree[th].value
+=
(tree[th].r
-
tree[th].l
+
1
)
*
tree[th].delta;
tree[th
*
2
].delta
+=
tree[th].delta, tree[th
*
2
+
1
].delta
+=
tree[th].delta;
tree[th].delta
=
0
;
}
if
(tree[th].l
==
l
&&
tree[th].r
==
r)
{
return
tree[th].value;
}
int
k
=
(tree[th].l
+
tree[th].r)
/
2
;
if
(r
<=
k)
{
return
sum(l, r, th
*
2
);
}
else
if
(l
>=
k
+
1
)
{
return
sum(l, r, th
*
2
+
1
);
}
else
{
return
sum(l, k, th
*
2
)
+
sum(k
+
1
, r, th
*
2
+
1
);
}
}
int
main()
{
int
n, m, i, x, y;
__int64 delta;
char
op[
2
];
scanf(
"
%d%d
"
,
&
n,
&
m);
for
(i
=
1
; i
<=
n; i
++
)
{
scanf(
"
%I64d
"
,
&
v[i]);
}
build(
1
, n,
1
);
while
(m
--
)
{
scanf(
"
%s
"
, op);
if
(
*
op
==
'
Q
'
)
{
scanf(
"
%d%d
"
,
&
x,
&
y);
printf(
"
%I64d\n
"
, sum(x, y,
1
));
}
else
{
scanf(
"
%d%d%I64d
"
,
&
x,
&
y,
&
delta);
update(x, y,
1
, delta);
}
}
system(
"
pause
"
);
return
0
;
}