Function HDU - 5875

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

对于a%b 若a<b则a%b==a不变 若a>=b则至少减小两倍 和取gcd有非常相似的性质 因为都利用到了取因数

对每个数 利用单调栈找到右边第一个比他小的数 查询时不断用nxt向后跳 最多计算log次

#include <bits/stdc++.h>
using namespace std;

struct node
{
    int id;
    int val;
};

stack <node> stk;
int ary[100010],nxt[100010];
int n,q;

int main()
{
    node tmp;
    int t,i,l,r,ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++) scanf("%d",&ary[i]);
        while(!stk.empty()) stk.pop();
        for(i=n;i>=1;i--)
        {
            while(!stk.empty()&&stk.top().val>ary[i]) stk.pop();
            if(stk.empty()) nxt[i]=n+1;
            else nxt[i]=stk.top().id;
            tmp.id=i,tmp.val=ary[i];
            stk.push(tmp);
        }
        scanf("%d",&q);
        while(q--)
        {
            scanf("%d%d",&l,&r);
            ans=ary[l];
            while(nxt[l]<=r)
            {
                l=nxt[l];
                ans%=ary[l];
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sunyutian1998/article/details/82152783