逆元 与等比数列求和

CodeForces - 964C
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 ∑i=0nsian−ibi∑i=0nsian−ibi by 109+9109+9.

Note that the modulo is unusual!

Input
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
Output a single integer — value of given expression modulo 109+9109+9.

Examples
Input
2 2 3 3
+-+
Output
7
Input

4 1 5 1

Output
999999228
Note
In the first example:

(∑i=0nsian−ibi)(∑i=0nsian−ibi) = 22302131+203222302131+2032 = 7

In the second example:

(∑i=0nsian−ibi)=−1450−1351−1252−1153−1054=−781≡999999228(mod109+9).

题意:给你n,a,b,k;有n+1项给你公式,然后给你前k项的符号;
从样例中可以看出,如果不看符号的话是个等比数列,我们知道等比数列,分块之后还是等比数列,公比则变为了q的k次方(前k项为首相);
所以 我们可以先求出来首项,加上符号求,然后等比数列求和就好;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9+9;
ll quick_mod(ll a,ll b, ll mod){
    ll ans = 1;
    a%= mod;
    while(b){
        if(b&1){
            b--;
            ans = (ans%mod*a%mod)%mod;
        }
        b>>=1;
        a = (a%mod*a%mod)%mod;
    }
    return ans;
}
int main()
{
    ll n,a,b,k;
    scanf("%lld%lld%lld%lld",&n,&a,&b,&k);

    string s;
    cin >> s;
    ll ans =  0;
    int x;
    for(ll i = 0; i < k; i++){//求首项
        if(s[i] == '+') x= 1;
        else x = -1;

        ans+= x*(quick_mod(a,n - i,mod)%mod*quick_mod(b,i,mod)%mod)%mod;
    }

    ll m = (n + 1)/k;
    ll q = (quick_mod(b,k,mod)%mod*quick_mod(a,k*mod - 2*k,mod)%mod)%mod;//求出分块之后的公比 (b/a)^k;

    if(q == 1) ans *= m;
    else{
        ans = (ans%mod*(1-quick_mod(q,m,mod))%mod*quick_mod(1-q,mod- 2, mod)%mod)%mod;//等比数列求和公式
    }
    ans = (ans%mod + mod)%mod;
    printf("%lld\n",ans);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值