您的位置:首页 > 其它

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

2016-06-21 21:52 309 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单调队列