Second My Problem First HDU - 3706 (单调栈,详细解释)

题意:给你三个数n,a,b,定义s[i]=a^i%b,T i = Min{ S k | i-A <= k <= i, k >= 1} ,要你求ti数组累成起来的积再取余b

思路:如果懂得单调栈的思想应该很容易就能想到这题要用单调栈来解决,模型不难建立,维护s[i]数组的单调递增序列然后每次把栈底元素累成起来取余b即可,只是这题要注意乘法溢出,我在这里wa了很久。详细看代码

#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e7+5;
LL n,a,b,ans;
int s[N],minn[N];
int main()
{
    int head,tail;
    while(~scanf("%lld%lld%lld",&n,&a,&b))
    {
        s[0]=1,head=0,tail=-1,ans=1;
        for(int i=1;i<=n;i++)
        {
            s[i]=s[i-1]*a%b;//这里要把a或者s数组开成long long型,不然会爆,如果开s数组的话内存会不够,所以把a开成long long型
            while(head<=tail&&s[i]<s[minn[tail]]) tail--;
            minn[++tail]=i;
            while(i-a>minn[head]) head++;//这里是要满足题目所说的i-a<=k,也就是说Ti是在a+1个s[i]中选择最小的一个
            ans=(ans*s[minn[head]])%b;//这里一样的道理,乘法溢出,将ans设成long long
        }
        printf("%lld\n",ans);
    }
}

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值