The shorter, the simpler. With this problem, you should be convinced of this truth.
You are given an array AA of NN postive integers, and MM queries in the form (l,r)(l,r). A function F(l,r) (1≤l≤r≤N)F(l,r) (1≤l≤r≤N) is defined as:
F(l,r)={AlF(l,r−1) modArl=r;l<r.F(l,r)={All=r;F(l,r−1) modArl<r.
You job is to calculate F(l,r)F(l,r), for each query (l,r)(l,r).
InputThere are multiple test cases. You are given an array AA of NN postive integers, and MM queries in the form (l,r)(l,r). A function F(l,r) (1≤l≤r≤N)F(l,r) (1≤l≤r≤N) is defined as:
F(l,r)={AlF(l,r−1) modArl=r;l<r.F(l,r)={All=r;F(l,r−1) modArl<r.
You job is to calculate F(l,r)F(l,r), for each query (l,r)(l,r).
The first line of input contains a integer TT, indicating number of test cases, and TT test cases follow.
For each test case, the first line contains an integer N(1≤N≤100000)N(1≤N≤100000).
The second line contains NN space-separated positive integers: A1,…,AN (0≤Ai≤109)A1,…,AN (0≤Ai≤109).
The third line contains an integer MM denoting the number of queries.
The following MM lines each contain two integers l,r (1≤l≤r≤N)l,r (1≤l≤r≤N), representing a query.OutputFor each query(l,r)(l,r), output F(l,r)F(l,r) on one line.Sample Input
1 3 2 3 3 1 1 3Sample Output
2
开一个next数组,next[i],表示i之后的第一个大于th[i]的数的位置,这样取余就不用挨个取了,因为可以跳着来,直接暴力的话肯定超时,因为取余运算太慢了
代码还算好理解,如下
#include <bits/stdc++.h>
using namespace std;
int n;
int th[100010];
int nest[100010];
int main()
{
int num;
scanf("%d", &num);
while(num --){
scanf("%d", &n);
for(int i = 1; i <= n; i ++){
scanf("%d", &th[i]);
}
for(int i = 1; i <= n; i ++){
for(int j = i + 1; j <= n; j ++){
nest[i] = n + 1;
if(th[i] >= th[j]){
nest[i] = j;
break;
}
}
}
//nest[n] = n + 1;
int m;
scanf("%d", &m);
for(int i = 0; i < m; i ++){
int l, r;
scanf("%d %d", &l, &r);
int ans = th[l];
if(l == r) cout << ans << endl;
else {
for(int j = nest[l]; j <= r; j = nest[j]){
if(th[j] == 0) break;
ans %= th[j];
if(ans == 0) break;
}
cout << ans << endl;
}
}
}
return 0;
}