hdu5875 Function (预处理+单调性质)

来源:互联网 发布:激光slam算法 编辑:程序博客网 时间:2024/05/22 05:04

Function
Time Limit: 7000/3500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)

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]只会减少而不会增加,从这一点我们可以预处理出当前点now可以跳跃到下一点的位置,因为后面比A[now]大的数都是无效的,所以我们直接跳过去。

没有很好的挖掘题目的条件并且自己独立思考,这样不利于自己的进步啊。

#include<bits/stdc++.h>using namespace std;const int maxn = 1e5+5;int A[maxn],n,Next[maxn];int main() {    int T,Q,u,v;    scanf("%d",&T);    while(T--) {        scanf("%d",&n);        for(int i=1; i<=n; ++i) {            scanf("%d",&A[i]);        }        for(int i=1; i<=n; ++i) {            Next[i]=-1;            for(int j=i+1; j<=n; ++j) {                if(A[i]>=A[j]) {                    Next[i]=j;                    break;                }            }        }        scanf("%d",&Q);        while(Q--) {            scanf("%d%d",&u,&v);            if(u==v) {                printf("%d\n",A[u]);            } else {                int ans=A[u];                for(int i=u; Next[i]<=v&&(~Next[i])&&ans; i=Next[i]) {                    ans%=A[Next[i]];                }                printf("%d\n",ans);            }        }    }    return 0;}
1 0
原创粉丝点击