hdu5875 Function 模运算 + 单调栈

题目描述:给定数组A,数组中元素的个数不多于1e5个,现给出函数F(l , r)的定义

                  给出m( m <= 1e5)次询问,每次询问给出l、r的值,每次输出F(l,r)

思路:首先观察模的三个性质:

           ①一个数模比它大的数大小不变

           ②一个数先模a,再模b,如果 a>b,那么模b这一步没什么效果

   ③a % b <= a/2

证明:若b >= a / 2 , 则 a % b = a - b <= a - a / 2 = a / 2 ;

    若b< a / 2  , 假设 a % b = x > a / 2 ;  则有x % b = y < x ,故a % b = y != x 矛盾

    综上,a% b <= a / 2 ;

          所以,对于任意一次询问,让A[i]只对其后面的第一个比自己小的数k取模,然后再对k后面比k小的第一个数取模,这样最多取模31次,复杂度O(logA[i] * m)不会超时

          那么,怎么维护比A[i]小的第一个数k呢?我们开一个数组nt,nt[i]表示第i个后面小于等于A[i]的第一个数的位置,使用单调栈构造nt数组。

  首先将a[n]入栈,然后i从n-1到1循环,每次如果a[i]大于等于栈顶的数,就把nt[i]赋值为栈顶数的位置;否则让栈顶的数出栈,考虑下一个栈顶。 最后,让a[i]入栈

  实现代码如下:

#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int maxn = 1e5 + 5;
const double eps=1e-6;
struct node{
    int val , pos ;
}st[maxn];
int top , a[maxn] ,  nt[maxn] ;
int main()
{
    int T , l , r , n , m ;
    scanf("%d",&T) ;
    while(T--){
        mem(st,0);  mem(nt , 0);
        top = 0;
        scanf("%d",&n);
        for(int i = 1 ; i<= n ; i++){
            scanf("%d",&a[i]);
        }
        node x = { a[n] , n } ;
        st[++top] = x ;
        nt[n] = -1 ;
        for(int i = n - 1 ; i>= 1 ; i--){
            int flag = 0;
            while(top > 0) {
                if(st[top].val <= a[i]){
                    nt[i] = st[top].pos ;
                    flag = 1 ;
                    break;
                }
                else{
                    --top;
                }
            }
            if(!flag)       nt[i] = -1 ;
            node x = {a[i] , i } ;
            st[++top] = x;
        }
        scanf("%d",&m);
        for(int i = 1 ; i<= m ; i++){
            scanf("%d %d",&l , &r);
            int cur = nt[l] , ans = a[l] ;
            while(cur != -1 && cur <= r && ans){
                int mod = a[cur] ;
                ans %= mod ;
                cur = nt[cur] ;
            }
            printf("%d\n",ans);
        }
    }
    return 0 ;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值