Function
Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 359 Accepted Submission(s): 135
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
2016 ACM/ICPC Asia Regional Dalian Online
数据好像不是很强。很容易知道,如果先mod一个数,再mod一个比它大的数,那么后面一次mod是一定不会使结果改变的。那么使用一个单调栈维护一个递增的数列,同时开一个pre【】,记录比i位置数字小的下一个位置是哪一个,然后在查询时,跳跃着查询就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
using namespace std;
int a[100005];
int pre[100005];
stack<int> st;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int N;
scanf("%d",&N);
memset(pre,-1,sizeof(pre));
while(!st.empty()) st.pop();
for(int i=1;i<=N;++i)
{
scanf("%d",&a[i]);
if(st.empty()||a[i]>=a[st.top()])
{
st.push(i);
}
else
{
while(!st.empty()&&a[i]<a[st.top()])
{
pre[st.top()]=i;
st.pop();
}
st.push(i);
}
}
int M;
int l,r;
scanf("%d",&M);
while(M--)
{
scanf("%d %d",&l,&r);
int tmp=a[l];
int temp=l;
while(pre[temp]<=r&&pre[temp]!=-1)
{
temp=pre[temp];
tmp%=a[temp];
}
printf("%d\n",tmp);
}
}
return 0;
}