单调队列1001 HDU 3706 Second My Problem First 单调队列入门题

Problem Description

Give you three integers n, A and B.
Then we define Si = Ai mod B and Ti = Min{ Sk | i-A <= k <= i, k >= 1}
Your task is to calculate the product of Ti (1 <= i <= n) mod B.
题意:
给n个数,第i个数是A^i%B,求sigma(T[i])
T[i]=min(Val[j])|j>=1&&j<=i&&j>=i-A
思路:
维护一个单调队列的入门题
单调队列是一个同时维护头指针和尾指针的双端队列
假设我们维护一个单调递减的单调队列
必须保证越靠近头指针越小
如果此时我们插入一个数x,我们从尾指针到头指针遍历
直到队列为空或者有个数小于x,如果遍历的时候不满足前边的条件
那么把这个队列里的元素扔出队列
由于我们每个元素只入出队列各一次,所以总是时间复杂度是O(n)的
而且单调队列中,入队时间永远是队头>=队尾
神奇的数据结构…ORZ

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 100005;
const int inf=(1<<28)-1;
deque<pair<LL,int> >Que;
int main()
{
    int n,A,mod; 
    while(~scanf("%d%d%d",&n,&A,&mod))
    {
        Que.clear();
        LL tmp=1,ans=1;
        for(int i=1;i<=n;++i)
        {
            tmp=(tmp*A)%mod;
            while(Que.empty()== 0 && tmp<=Que.back().first)
            Que.pop_back();
            Que.push_back(make_pair(tmp,i));
            while(Que.empty()== 0 &&i-Que.front().second>A)
            Que.pop_front();
            ans=(ans*Que.front().first)%mod;
        }
        printf("%lld\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值