HDU-5875-Function

本文介绍了一道来自HDU在线评测系统的题目,该题要求通过模运算求解数组中特定范围内的数值。文章提供了一种解决方案,即预先计算每个元素后方最近的小于它的元素的位置,以此来优化查询过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:http://acm.hdu.edu.cn/showproblem.php?pid=5875

题意:给定数组a[],m 个询问L,R,求a[L],依次取模a[L+1]...a[R]后的值。

题解:找出每个数后面第一个比他小的数的位置,但在最坏的情况下还是O(mn)。。。

CODE:

#include <bits/stdc++.h>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define INF 0x3f3f3f3f
#define LL long long
#define bug cout<<"bug"<<endl
const int MAXN = 200007;
const int MAXM = 20007;
const int MOD = 1e9 + 9;
using namespace std;
int a[MAXN],link[MAXN];
stack<int> s;
int main()
{
    int T;
    scanf("%d",&T);
    int n,m;
    while(T--)
    {
        scanf("%d",&n);
        memset(link,0,sizeof(link));
        while(!s.empty())s.pop();
        for(int i=1; i<=n; ++i)
        {
            scanf("%d",&a[i]);
            while(!s.empty()&&a[s.top()]>=a[i])
            {
                link[s.top()]=i;
                s.pop();
            }
            s.push(i);
        }
        int l,r;
        scanf("%d",&m);
        for(int i=0; i<m; ++i)
        {
            scanf("%d%d",&l,&r);
            int x=a[l];
            while(link[l] && link[l]<=r)
            {
                l=link[l];
                x%=a[l];
            }
            printf("%d\n",x);
        }
    }
    return 0;
}
/*
1
3
2 3 3
1
1 3
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值