题意:给你三个数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