HDU 5875 Function(预处理)

来源:互联网 发布:java aop实现原理 编辑:程序博客网 时间:2024/05/19 03:44

Function
Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1242    Accepted Submission(s): 457

 

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


 


Source

 2016 ACM/ICPC Asia Regional Dalian Online 

题意:询问(L,R)a[l]%a[l+1].....%a[r]的值。

题解:比赛中其实想到了预处理,不过想的是直接预处理出[L,R],然后a[l]直接对内个值求余即可,后来发现这很SB,后来又想到线段树(线段树也能求,思想一样),然后就没然后了。  正解是预处理(L,R)内比a[l]小的数,用数组存比a[l]小的数的下标,这样大大节约时间。

 

代码:

#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <queue>#include <vector>#include <cmath>#include <set>#include <map>#include <algorithm>#define LL long long#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;const int maxn = 100005;int a[maxn],nt[maxn];int n,m,x,y,t;void itin()//预处理{    memset(nt,-1,sizeof(nt));    for(int i=1;i<=n;i++)    {        for(int j=i+1;j<=n;j++)        {            if(a[j]<a[i])            {                nt[i]=j;                break;            }        }    }}int main(){    scanf("%d",&t);        while(t--)        {            scanf("%d",&n);            for(int i=1;i<=n;i++)            {                scanf("%d",&a[i]);            }            itin();            scanf("%d",&m);            while(m--)            {                scanf("%d%d",&x,&y);                int ans=a[x];                for(int i=nt[x];i!=-1&&i<=y;i=nt[i])                {                    ans%=a[i];                }                printf("%d\n",ans);            }        }    }


 

 

0 0
原创粉丝点击