You are given two integers aa and bb. Moreover, you are given a sequence s0,s1,…,sns0,s1,…,sn. All values in ss are integers 11 or −1−1. It's known that sequence is kk-periodic and kk divides n+1n+1. In other words, for each k≤i≤nk≤i≤n it's satisfied that si=si−ksi=si−k.
Find out the non-negative remainder of division of n∑i=0sian−ibi∑i=0nsian−ibi by 109+9109+9.
Note that the modulo is unusual!
The first line contains four integers n,a,bn,a,b and kk (1≤n≤109,1≤a,b≤109,1≤k≤105)(1≤n≤109,1≤a,b≤109,1≤k≤105).
The second line contains a sequence of length kk consisting of characters '+' and '-'.
If the ii-th character (0-indexed) is '+', then si=1si=1, otherwise si=−1si=−1.
Note that only the first kk members of the sequence are given, the rest can be obtained using the periodicity property.
Output a single integer — value of given expression modulo 109+9109+9.
2 2 3 3 +-+
7
4 1 5 1 -
999999228
In the first example:
(n∑i=0sian−ibi)(∑i=0nsian−ibi) = 2230−2131+20322230−2131+2032 = 7
In the second example:
(n∑i=0sian−ibi)=−1450−1351−1252−1153−1054=−781≡999999228(mod109+9)(∑i=0nsian−ibi)=−1450−1351−1252−1153−1054=−781≡999999228(mod109+9)
思路:因为每一项的正负是循环的,循环节的大小是k,并且保证了(n+1)是k的倍数。并且抛开正负不看的话这是一个等比数列,加上正负的话,因为正负是循环有规律的原因,我们可以把式子等分,每一份为k项,当成一个新的等比数列,k项为新等比数列中的一项,等比数列求和公式即可解出答案。
但是要注意还有取模的操作,因为我们在计算的时候会涉及公比(b/a)^k,而当a>b的时候取模就会爆精度。在这里就要通过求a的逆元来化除为乘。如果对逆元不了解的话,可以移步https://blog.csdn.net/baymax520/article/details/79997102
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
const int mod=1e9+9;
long long quickpow(long long a,long long b)//快速幂
{
long long ans=1;
a%=mod;
while(b)
{
if(b&1)
ans=(ans*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ans;
}
long long inv(long long a)//费马小定理求逆元
{
return quickpow(a,mod-2);
}
int main()
{
char s[100005];
int n,a,b,k,i;
while(scanf("%d %d %d %d",&n,&a,&b,&k)!=EOF)
{
scanf("%s",s);
long long sum=0;
for(i=0;i<k;i++)//先求出前k项的和
{
if(s[i]=='+')
sum=(sum+quickpow(a,n-i)*quickpow(b,i)%mod+mod)%mod;
else
sum=(sum-quickpow(a,n-i)*quickpow(b,i)%mod+mod)%mod;
}
long long t=quickpow(b,k)*inv(quickpow(a,k))%mod;//使用逆元求公比(b/a)^k
if(t==1)//公比为1和不为1的时候计算不同
{
sum=(sum*(n+1)/k)%mod;
printf("%I64d\n",(sum+mod)%mod);
}
else
{
sum=sum*(quickpow(t,(n+1)/k)-1)%mod*inv(t-1)%mod;
printf("%I64d\n",sum);
}
}
return 0;
}