2016 百度之星资格赛 A题

画图说话:

前缀积推导

分析:9937 为质数,费马小定理+逆元,除法变乘法,快速幂取余

费马小定理

公式推导:(b/a)mod p=> (b*a的逆元)mod p 根据费马小定理,a^(p-1) =1 mod p <=> a^(p-2) a= 1 mod p <=> a的逆元为 a^(p-2),所以(b/a)mod p <=>(ba^(p-2)) mod p

用到的板子:快速幂取余、前缀积

快速幂取余

// x是底数,n是幂数,mod是取余数
LL mod_pow(LL x,LL n,LL mod)
{
    LL res = 1;
    while(n>0)
    {
        if(n & 1)
        {
            res = res * x % mod;
        }
        x = x * x % mod;
        n >>= 1;
    }
    return res;
}

前缀积

H[0] = 1;
for(int i = 1 ;i<=len;i++)
    {
          H[i]=H[i-1]*(Hstr[i-1]-28)%mods;
    }

AC代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAXN = 1e5 + 5;
int H[MAXN];
char Hstr[MAXN];
int N,l,r;
const int mods = 9973;
typedef long long LL;

//快速幂取余
LL mod_pow(LL x,LL n,LL mod)
{
    LL res = 1;
    while(n>0)
    {
        if(n & 1)
        {
            res = res * x % mod;
        }
        x = x * x % mod;
        n >> 1;
    }
    return res;
}

int main ()
{
    while(scanf("%d",&N)!=EOF)
    {
        scanf("%s",Hstr);
        int len =strlen(Hstr);
        H[0] = 1;
        for(int i = 1 ;i<=len;i++)
        {
            H[i]=H[i-1]*(Hstr[i-1]*28)%mods;
        }
        while(N--)
        {
            scanf("%d%d",&l,&r);
            if(l>r)
            {
                swap(l,r);
            }
            printf("%I64D
",(LL)H[r]*mod_pow(H[l-1],mods-2,mods)%mods);
        }
    }
}
原文地址:https://www.cnblogs.com/xzmds/p/5503832.html