C .generator 2 (BSGS详解) 2019牛客暑期多校训练营(第五场)

题目大意:

       一个n项的数列,x^{n}=a*x^{n-1}+b    Q次询问输入一个v求最小的下标 i 使得X i == v。

题目思路:

                                                                      Xn=a*Xn-1+b

写出通项公式,也就是把Xn-1 ,一项一项拆开后:

                                                       Xn=a^{n}{X_{0}}+a^{n-1}b+a^{n-2}b+...+ab+b 

把后边的b提取公因式之后留下的a是个等比数列:

                                                                   {X_n}=a^{n}*{X_0}+b*\frac{1-a^{n}}{1-a}

合并同类项 :

                                                               a^{n}=\frac{v*(1-a)-b}{​{X_0}*(1-a)-b} (mod p)

直接BSGS就可以了

如果m还按照\sqrt{p}的话会超时。代码中的小步设置为p^(1/3)

#include<bits/stdc++.h>
#define ll long long
using namespace std;
unordered_map<ll,ll>mp;
ll p,a,b,x0,v,n;
ll Pow(ll a,ll b)
{
    ll ans=1ll;
    while(b){
        if(b&1)ans=ans*a%p;
        a=a*a%p;
        b>>=1;
    }
    return ans;
}

ll last,Giant,Baby;
void init_BSGS()
{
    mp.clear();
    Giant = ceil(pow(p,2.0/3)); ///j
    ll now = 1;
    for(ll i=0;i<=Giant;i++){
        if(i == Giant) last = now;
        mp[now] = i;
        now = now * a % p;
    }
}
ll BSGS(ll a,ll b ,ll p)
{
    ll Baby = ceil(pow(p,1.0/3));
    ll nb = Pow(b,p-2);
    for(ll i=1;i<= Baby;i++){   ///i
        nb = nb * last % p;
        if(mp.count(nb)){
            return i* Giant - mp[nb];
        }
    }
    return -1;
}
int main()
{
    ll t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld%lld%lld%lld%lld",&n,&x0,&a,&b,&p);
        ll q;
        scanf("%lld",&q);
        ll invb = Pow(b,p-2);
        init_BSGS();
        while(q--)
        {
            scanf("%lld",&v);
            if(a==0){
                if(x0==v)printf("0\n");
                else if(b==v)printf("1\n");
                else printf("-1\n");
                continue;
            }
            else if(a==1){
                ll ans=((v-x0 + p) * invb % p +p)%p;
                if(ans<n)printf("%lld\n",ans);
                else printf("-1\n");
                continue;
            }

            ll base=( (x0* (1-a+p) %p) - b + p )%p;       ///
            ll fro =( (v * (1-a+p) %p) - b + p )%p;
            v= fro * Pow(base,p-2) % p;

            ll ans = BSGS(a , v , p);
            if(ans<n)printf("%lld\n",ans);
            else printf("-1\n");
            continue;
        }
    }
}
/*
1000000000000000000 1 5 0 1000000007
6
0
1
10
1000000006
12345678
1234567
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值