Function
Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1459 Accepted Submission(s): 539
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
给出[l,r] 求解a[l]%a[l+1]%a[l+2]%……%a[r]
如果a[i] < a[j]
a[i]%a[j]=a[i]
所以每次只需要找<=当前值的数进行取模
问题就在怎样预处理一遍 找出一个对应的递减序列
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
#include<bitset>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
const int N=100000+5;
int a[N];
int Next[N];//next[i]为a[i]右边 第一个<=a[i]的数的下标
void ini(int n){
fill(Next,Next+n+1,0);
for(int i=n-1;i>=1;--i)
for(int j=i+1;j<=n;){
if(a[j]<=a[i]){//当a[j]比a[i]小 更新next[i] 跳出
Next[i]=j;
break;
}
//a[j]后方没有比a[j]更小的了 所以a[i]>a[j] j>i Next[i]不存在
if(!Next[j])
break;
j=Next[j];//j=第一个比a[j]小的数的下标
}
}
int main()
{
//freopen("/home/lu/文档/r.txt","r",stdin);
//freopen("/home/lu/文档/w.txt","w",stdout);
int t,n,m,l,r;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=1;i<=n;++i)
scanf("%d",a+i);
ini(n);
scanf("%d",&m);
while(m--){
scanf("%d%d",&l,&r);
int ans=a[l];
for(int i=l+1;i<=r&&i>0;){
ans%=a[i];
if(ans==0)
break;
i=Next[i];
}
printf("%d\n",ans);
}
}
return 0;
}