Problem:
Score : 600 points

Problem Statement

We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.

Process the following q queries in order:

The i-th query contains three integers n_i, x_i, and m_i.
Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray}
Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).

Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).

Constraints

All values in input are integers.

1 \leq k, q \leq 5000

0 \leq d_i \leq 10^9

2 \leq n_i \leq 10^9

0 \leq x_i \leq 10^9

2 \leq m_i \leq 10^9

Input

Input is given from Standard Input in the following format:

k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q

Output

Print q lines.

The i-th line should contain the response to the i-th query.

Sample Input 1

3 1
3 1 4
5 3 2

Sample Output 1

1

For the first query, the sequence {a_j} will be 3,6,7,11,14.

(a_0~\textrm{mod}~2) > (a_1~\textrm{mod}~2)

(a_1~\textrm{mod}~2) < (a_2~\textrm{mod}~2)

(a_2~\textrm{mod}~2) = (a_3~\textrm{mod}~2)

(a_3~\textrm{mod}~2) > (a_4~\textrm{mod}~2)

Thus, the response to this query should be 1.

Sample Input 2

7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12

Sample Output 2

224489796
214285714
559523809

Solution in C++ (GCC 9.2.1) (judge verdict: Time Limit Exceeded)

#include<iostream>
using ll = long long;
using namespace std;

ll D[5050];

// atcoder library より
long long floor_sum(long long n, long long m, long long a, long long b) {
    long long ans = 0;
    if (a >= m) {
        ans += (n - 1) * n * (a / m) / 2;
        a %= m;
    }
    if (b >= m) {
        ans += n * (b / m);
        b %= m;
    }

    long long y_max = (a * n + b) / m, x_max = (y_max * m - b);
    if (y_max == 0) return ans;
    ans += (n - (x_max + a - 1) / a) * y_max;
    ans += floor_sum(y_max, a, m, (a - x_max % a) % a);
    return ans;
}

int main(){
  ll K, Q; cin >> K >> Q;
  for(int i=1;i<=K;i++){
    // 累積和にしておく
    cin >> D[i];
    D[i] += D[i-1];
  }
  for(int q=0;q<Q;q++){
    ll N, X, M; cin >> N >> X >> M;
    ll ans = 0;
    for(int i=0;i<K;i++){
      // j = i, i+K, i+2K, ... についての集計をする
      if(i > N-2) break;
      ll n_max = (N-2-i)/K;
      ll a = D[K] % M;
      ll b = (X + D[i]) % M;
      ll y = (M - (D[i+1]-D[i])% M) % M;
      
      // 0 <= a * n + b mod M < y となる n in [0, n_max] を数え上げる
      ll x = floor_sum(n_max + 1, M, a, b);
      
      // x -= floor_sum(n_max + 1, M, a,b - y); としたい。
      // atcoder library floor sum は 負数には対応していないので調整する。
      x -= floor_sum(n_max+1, M, a, b-y+M) - (n_max+1);
      ans += x;
    }
    cout << ans << endl;
  }
  return 0;
}