The exercise is as follows:
Player A will write list \$ a \$ consisting of \$ n \$ numbers. Player B will take a look at the paper. After that the A player will ask player B \$q\$ questions. Each question will be of the following form:
If I give you two \$ R \$ and \$ L \$ in \$ a \$ such that (\$ 1<=L<=R<=n\$ ), calculate the following value:
$$ 1*a[L] + 2*a[L+1] + 4*a[L+2] + ... + 2^{R-L-1}*a[R-1]+2^{R-L}*a[R] $$
Because the numbers can be really large, we need to find the residue that the result will give when divided by \$ 10^9 + 7\$.
Input is as follows:
n q a1 a2 an L1 R1 L2 R2 Lq RqThe output is: on one line the result for one query.
The problem:
I need to improve performance so it is finished within 1 second. I think the problem may be because I have 2 for loops. Because the number of numbers can be up to 200,000 as well as the pairs. This means that in the worst case it has to go through the process 40,000,000,000 times.
Can someone please tell me how to improve the performance?
#include <iostream> using namespace std; const int MAXN = 200000; int residues[MAXN]; int numbers[MAXN]; int pairs[MAXN][2]; void findResidues(int i) { residues[i] = (residues[i - 1] * 2) % 1000000007; } long long int sumBetween(int first, int second) { long long int sum = 0; int pos = first; while(pos <= second) { sum += (long long)residues[pos - first] * numbers[pos]; sum %= 1000000007; pos++; } return sum; } int main() { residues[0] = 1; int n, q ; cin >> n >> q; for(int i = 0; i < n; i++) { cin >> numbers[i]; findResidues(i + 1); } for(int i = 0; i < q; i++) { cin >> pairs[i][0] >> pairs[i][1]; cout << sumBetween(pairs[i][0] - 1, pairs[i][1] - 1) << endl; } return 0; }