描述:
Function
Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 311 Accepted Submission(s): 109
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) .
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.
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
Source
Recommend
题意:
给出长度为n的正整数序列,m个询问[l,r]
f(l,r) = f(l,r-1)%a[r] l<r
f(l,r) = a[r] l=r
对于每个询问[l,r],输出f(l,r)的值
思路:
可以推出f(l,r)=a[l]%a[l+1]%...%a[r]
对于当前的l,在其右边只可能是比它小的数才会对答案造成影响,并且是递减的小(越来越小),注意这里不是比取模之后的答案还小
考虑从左往右遍历,但是要每次跳过比它大的那些数,直接指向它右边第一个比它小的。
显然这样做的这样复杂度是不定的……最坏的情况还是O(NM),即所有的数据都是降序的。可是数据水。
这场比赛的一个特点就是看似题目难,然而数据水,乱搞就能过。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
const int inf=0x3f3f3f3f;
int a[maxn],r[maxn];
int main(){
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=1; i<=n; i++){
scanf("%d",&a[i]);
}
memset(r, inf, sizeof(r));
for(int i=n-1; i>=1; i--){
int k=i+1;
while(1){
if(a[i]>a[k]){
r[i]=k;
break;
}
if(r[k]==inf)break;
k=r[k];
}
}
int m;
scanf("%d",&m);
while(m--){
int x,y;
scanf("%d%d",&x,&y);
int ans=a[x];
x=r[x];
while(x<=y){
ans%=a[x];
if(ans==0)break;
x=r[x];
}
printf("%d\n",ans);
}
}
return 0;
}