Second My Problem First 单调栈

Give you three integers n, A and B. 
Then we define S i = A i mod B and T i = Min{ S k| i-A <= k <= i, k >= 1} 
Your task is to calculate the product of T i (1 <= i <= n) mod B.

Input

Each line will contain three integers n(1 <= n <= 10 7),A and B(1 <= A, B <= 2 31-1). 
Process to end of file.

Output

For each case, output the answer in a single line.

Sample Input

1 2 3
2 3 4
3 4 5
4 5 6
5 6 7

Sample Output

2
3
4
5
6

单调栈裸题

维护一个单调栈

栈内元素从小到大

栈内的所有的id元素也是从小到大

这样我们每次查询栈头元素就是我们要查询的最小值了

代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    #endif
    long long n, a, b;
    while(~scanf("%lld%lld%lld",&n,&a,&b))
    {
        deque<pair<int,int> > q;//保证单调递增
        long long ans=1;
        long long tmp=1;
        for (int i = 1; i <= n; i++)
        {
            tmp=(tmp*a)%b;
            while(q.size()&&q.back().first>tmp) q.pop_back();
            q.push_back(make_pair(tmp,i) );
            while(i-q.front().second>a) q.pop_front();
            ans=(ans*q.front().first)%b;
        }
        printf("%lld
",ans);
    }
}
原文地址:https://www.cnblogs.com/caowenbo/p/11852229.html