Problem Description
The shorter, the simpler. With this problem, you should be convinced of this truth.
You are given an array A of N postive integers, and M queries in the form (l,r). A function F(l,r) (1≤l≤r≤N) is defined as:
F(l,r)={AlF(l,r−1) modArl=r;l<r.
You job is to calculate F(l,r), for each query (l,r).
Input
There are multiple test cases.
The first line of input contains a integer T, indicating number of test cases, and T test cases follow.
For each test case, the first line contains an integer N(1≤N≤100000).
The second line contains N space-separated positive integers: A1,…,AN (0≤Ai≤109).
The third line contains an integer M denoting the number of queries.
The following M lines each contain two integers l,r (1≤l≤r≤N), representing a query.
Output
For each query(l,r), output F(l,r) on one line.
Sample Input
1
3
2 3 3
1
1 3
Sample Output
2
题意:给出 n 个数,然后给出一个区间,求出这个区间中的第一个数不断向后取模预算到最后的结果。
因为和比自己大的数取模的结果还是他自己,所以只需要和自己小的数取模即可。做一个数组专门用来储存这个数后面第一个比他小的,这样每次找后一个并且取模。
#include <cstdio>
int num[100000 + 5];
int next[100000 + 5];
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i)
scanf("%d", &num[i]);
for (int i = 0; i < n; ++i)
{
next[i] = -1;
for (int j = i + 1; j < n; ++j)
{
if (num[j] <= num[i])
{
next[i] = j;
break;
}
}
}
int t;
scanf("%d", &t);
while (t--)
{
int left, right;
scanf("%d%d", &left, &right);
left--;
int ans = num[left];
for (int i = next[left]; i < right; i = next[i])
{
if (i == -1)
break;
ans %= num[i];
}
printf("%d\n", ans);
}
}
return 0;
}