1

Given a one dimensional integer array A of length N. We need Q queries each of one of following types:

NOTE : M is fixed to be 10^9 + 7

Query 1 : 1 x y v : It means adding v to all element from x to y in 1 base indexed array and then take them modulo M.

for (i = x; i <= y; i++)    
    A[i] += v;
    A[i] %= M; 

Query 2 : 2 x y v : It means multiplying v to all element from x to y in 1 base indexed array and then take them modulo M.

for (i = x; i <= y; i++)    
    A[i] *= v
    A[i] %= M

Query 3 : 3 x y v : It means substituting v to all element from x to y in 1 base indexed array.

for (i = x; i <= y; i++)    
    A[i] = v 

Query 4 : 4 x y : This is a report query which needs to find the sum of the values in A from x to y, i.e.,

sum = 0;
for (i = x; i <= y; i++)
    sum += A[i]
    sum %= M
Output sum.

Now how to handle these queries ? I know to handle queries if it were addition and sum queries with segment tree. But have no idea for this one. Please help me to solve this problem.

Constraints : 1 ≤ N,Q ≤ 10^5 and 1 ≤ Initial value of A[i],v ≤ 10^9

Cœur
  • 37,241
  • 25
  • 195
  • 267
ms8
  • 417
  • 2
  • 13
  • what do you mean "how to handle?" You have good pseudocode in the question already. What are you actually asking here? – chiliNUT Jul 04 '15 at 16:58
  • in the Query 4: "sum %= M" you sure you want this... you mod your sum and then add to it... ? – jdl Jul 04 '15 at 17:00
  • @jdl Yeah.. I need to do this way – ms8 Jul 04 '15 at 17:01
  • @chiliNUT I cant do this way reason being the count of such queries is very large. – ms8 Jul 04 '15 at 17:01
  • @chiliNUT Please read problem carefully. Its taking MOD at each step. So there is no need of such library – ms8 Jul 04 '15 at 17:04
  • Your arrays of 10,000 don't seem that large. What's the problem with what you wrote? Implement it in c, and see if there's a problem at all. The stuff also seems pleasingly parallel, BTW. – Ami Tavory Jul 04 '15 at 17:10
  • @AmiTavory Suppose we have 10^5 elements and 10^5 queries then each query is in worst will be running in O(N) that is 10^5. so total complexity becomes 10^5 * 10^5 that is not affordable – ms8 Jul 04 '15 at 17:12
  • No time to write an answer now, but you can use segment trees/lazy propagation/linear polynomials over (**Z**/M)[x] under composition. – David Eisenstat Jul 04 '15 at 17:23
  • (If you edit the question for another reason, please correct the title.) See also [Using lazy propagation for Add to & Initialize a range, Multiply scalar or report running sum](http://stackoverflow.com/q/31224883/3789665). – greybeard Jul 05 '15 at 01:26
  • @FalconUA I know Fenwick Tree . But how this can be solved by them ? Can you please elaborate – ms8 Jul 05 '15 at 04:42
  • @greybeard I know Lazy Propogation. But how it will help here ? – ms8 Jul 05 '15 at 04:42

0 Answers0