Professional Documents
Culture Documents
Editorial For Series-Sum-1 in Algos-Inductions-Round-1: O (N Q) L, R N
Editorial For Series-Sum-1 in Algos-Inductions-Round-1: O (N Q) L, R N
Editorial For Series-Sum-1 in Algos-Inductions-Round-1: O (N Q) L, R N
The steps involved in the naive approach to solve this question is,
The time complexity of this method is O(n*q), as for each query, the range given by l, r can be n.
As, you might have guessed, this method will work fine for the initial test-cases. But for it to satisfy
bigger test cases, we need a better algorithm.
I saw a lot of people writing the following function for finding f[i]
This function takes exponential time to compute value of f[i] as the same values are going to be
passed again and again. So, a better is fairly simple. Run a for loop to calclate the value of f[i] and
store it in an array.
The source code for this arroach is given below. Do ask if you find any difficulty in understand any
part. In the code, the array p is used instead of x. Too lazy to change :p.
#include <bits/stdc++.h>
int main() {
ll n, q;
cin>>n>>q;
ll f[n + 2];
cin>>f[0]>>f[1];
ll a, b, i;
a = 3; b = 4;
rep(i, 2, n+1) {
f[i] = ((a * f[i-2]) % mod + (b * f[i-1]) % mod) % mod;
}
ll p[n + 2] = {0};
while(q--) {
ll l, r;
cin>>l>>r;
l--; r--;
if(l < r) {
p[l] = (p[l] + f[0]) % mod;
p[l + 1] = (((p[l + 1] + f[1]) % mod) + mod - ((b * f[0]) % mod)) % mod;
cout<<p[i]<<" ";
}
return 0;
}