Function
Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 1427 Accepted Submission(s): 126
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
#include <iostream>
#include <cstdio>
#define MAXN 100005
using namespace std;
int a[MAXN];
int temp[MAXN];
int n,m,l,r;
void Init()
{
for(int i = 1; i<=n; i++)
{
temp[i] = i;
for(int j = i+1; j<=n; j++)
{
if(a[j] < a[i])
{
temp[i] = j;
break;
}
}
}
}
void solve()
{
if(l == r)
printf("%d\n",a[l]);
else
{
int ans = a[l];
for(int i = l+1; i<=r; )
{
ans = ans %a[i];
if(temp[i] != i)
i = temp[i];
else
i++;
}
printf("%d\n",ans);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i = 1; i<=n; i++)
scanf("%d",&a[i]);
scanf("%d",&m);
Init();
while(m--)
{
scanf("%d%d",&l,&r);
solve();
}
}
return 0;
}