codeforces 963A/964C Alternating Sum【数学】

题目大意:给你一个n,a,b,k
有n+1个数据,让你求 i = 0 n s i a n i b i 答案取模1e9+9
条件是这n+1个数据每k个是一个循环
1 < n , a , b <= 1 e 9 , 1 < k <= 1 e 5

题目分析 如果我们让第i+k项比上第i项就可以发下只剩下 b k / a k
q = b k a k 我们只要暴力求解前k项,整个公式就变成了一个等比数列求和
直接用公式算的话,注意q=1的情况

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 50;
const int mod = 1e9 + 9;
ll qpow(ll a, ll b)
{
    ll base = a;
    ll ans = 1;
    while (b)
    {
        if (b & 1)
        {
            ans = (ans * base) % mod;
        }
        base = (base * base) % mod;
        b = b >> 1;
    }
    return ans;
}
ll n, a, b, k;
string s;
int main()
{

    cin >> n >> a >> b >> k;
    cin >> s;
    ll a1 = 0;
    for (int i = 0; i<s.size(); i++)
    {
        ll flag = 1;
        if (s[i] == '-')
        {
            flag = -1;
        }

        a1 = (a1 + flag * (qpow(a, n - i)*qpow(b, i)) % mod + mod) % mod;
        //cout << qpow(a, n - i) << endl;
        //cout << qpow(b, i) << endl;
        //cout << a1 << endl;

    }
    ll m = (n + 1 )/ k;
    ll ak = qpow(a, k);
    ll bk = qpow(b, k);
    ll x = qpow(ak, mod - 2);

    ll q = (bk*x) % mod;
   // cout<<q<<" 1"<<endl;
   ll ans=0;
   if(q!=1)
   {
     ans = (a1*((qpow(q,m)-1))%mod + mod) % mod;
    //ll ans = (a1*(q-1)) % mod;
//cout<<qpow(2,mod-2)<<endl;
    ll t1 = qpow(q - 1, mod - 2);
    ans = (ans*t1) % mod;
   }
   else
   {
       ans=(a1*m)%mod;
   }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/becky_w/article/details/80005409

相关文章