zoukankan      html  css  js  c++  java
  • HDU5875Function(单调队列)

    The shorter, the simpler. With this problem, you should be convinced of this truth. 
       
      You are given an array AA of NN postive integers, and MM queries in the form (l,r)(l,r). A function F(l,r) (1lrN)F(l,r) (1≤l≤r≤N) is defined as: 
    F(l,r)={AlF(l,r1) modArl=r;l<r.F(l,r)={All=r;F(l,r−1) modArl<r. 
    You job is to calculate F(l,r)F(l,r), for each query (l,r)(l,r).

    InputThere are multiple test cases. 
       
      The first line of input contains a integer TT, indicating number of test cases, and TT test cases follow. 
       
      For each test case, the first line contains an integer N(1N100000)N(1≤N≤100000). 
      The second line contains NN space-separated positive integers: A1,,AN (0Ai109)A1,…,AN (0≤Ai≤109). 
      The third line contains an integer MM denoting the number of queries. 
      The following MM lines each contain two integers l,r (1lrN)l,r (1≤l≤r≤N), representing a query.
    OutputFor each query(l,r)(l,r), output F(l,r)F(l,r) on one line.

    Sample Input

    1
    3
    2 3 3
    1
    1 3

    Sample Output

    2

    题意:

    已知a[]数组,现在给出m组l,r。求a[l]%a[l+1]%a[l+2]%...a[r]的结果。

    思路:

    a[l]<a[l+1],那么这个膜运算是可以忽视的。单调队列,逆序预处理出每一个a[]的右边第一个小于a[]的数的位置R[],然后就是用a[l]%a[R[l]]%a[R[R[l]]]...。

    #include<cstdio>
    #include<cstdlib>
    #include<iostream>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    const int maxn=1000010;
    int a[maxn],R[maxn];
    int main()
    {
        int n,m,T,i,j,l,r,t,ans;
        scanf("%d",&T);
        while(T--){
            scanf("%d",&n);
            for(i=1;i<=n;i++) scanf("%d",&a[i]);
            for(i=1;i<=n+1;i++) R[i]=n+1; a[n+1]=0;
            for(i=n-1;i>=1;i--){
                t=i; 
                while(t<n){                       // 得到R数组 
                    if(a[t+1]<a[i]){ R[i]=t+1; break;}
                    if(a[R[t+1]]>=a[i]) t=R[t+1];
                    else {
                        for(j=t+1;j<=R[t+1];j++) {//这里可以二分优化 
                            if(a[j]<a[i]) {
                                 R[i]=j;break;
                            }
                        } break;
                    }
                }
            }
            scanf("%d",&m);
            while(m--){
                scanf("%d%d",&l,&r);
                ans=a[l];t=l;
                while(R[t]<=r){                    //过滤掉无用的膜运算 
                    t=R[t];
                    ans%=a[t];
                }
                printf("%d
    ",ans);
            }
        }  return 0;
    }
  • 相关阅读:
    kb-07线段树-12--二分查找区间边界
    kb-07线段树--11--区间多重该值多种查询
    kb-07线段树--10--dfs序建树
    kb-09-线段树--区间合并比较繁
    kb-07线段树-08--区间开根
    kb-07-RMQ线段树--07(动态规划)
    kb-07线段树-06离散化(与第四题类似)
    kb-07线段树-05-区间整体修改查询;(水)
    poj-2486-Apple Tree
    mnist的数据预处理
  • 原文地址:https://www.cnblogs.com/hua-dong/p/8099335.html
Copyright © 2011-2022 走看看