Efficent Algorithm to Answer Subarray Queries fast

Viewed 261

The other day I encountered a problem related with queries, but I can't solve it.

Given an array with N integers and a positive integer M, you must answer Q queries. Each query is characterized as ( i , j ), where i and j are each indices of the array. In each query you must answer how many pairs ( r , s ) exist such that

  1. i <= r <= s <= j
  2. the sum of the array elements with indices in [ r , s ] is divisible by M.

Limits:

N <= 50,000
Q <= 50,000
M <= 100

I have a dynamic programming solution that preprocesses every query ( r , s ) in O( N^2 ), but that is not fast enough. Is there a more efficient solution? I have some ideas with Mo's algorithm, or with segment trees, but I can't get it.

2 Answers
Related