Luogu5431 【模板】乘法逆元2

https://www.luogu.com.cn/problem/P5431

乘法逆元

注意,不能暴力算,否则必然\(TLE\)

需要先通分,然后简单计算,从而优化时间复杂度

还需要火车头

\(C++ Code:\)

#pragma GCC optimize(O2)
#pragma GCC optimize(O3)
#pragma GCC optimize(Ofast)
#pragma GCC optimize("inline")
#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
#define N 5000005
using namespace std;
int n,p,k;
int a[N],qz[N],hz[N];
template<typename T>
inline void read(T &x) 
{
    x=0;
    T otz=1,ch=getchar();
    while (!isdigit(ch)&&ch!='-') 
        ch=getchar();
    if(ch=='-') 
    {
    	otz=-1;
        ch=getchar();
    }
    while (isdigit(ch)) 
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    x*=otz;
}
template<typename T>
inline void write(T x)
{
    if (x<0)
    {
        x=-x;
        putchar('-');
    }
    if (x>=10)
        write(x/10);
    putchar(x%10+'0');
}
ll ksm(ll x,ll y)
{
    ll ans=1;
    while (y)
    {
        if (y & 1)
            ans=ans*x%p;
        x=x*x%p;
        y >>=1;
    }
    return ans;
}
int main()
{
    read(n),read(p),read(k);
    qz[0]=1;
    for (int i=1;i<=n;i++)
    {
        read(a[i]);
        qz[i]=(ll)qz[i-1]*a[i]%p;
    }
    hz[n+1]=1;
    for (int i=n;i>=1;i--)
        hz[i]=(ll)hz[i+1]*a[i]%p;
    ll s1=ksm(qz[n],p-2);
    ll s=1,ans=0;
    for (int i=1;i<=n;i++)
    {
        s=s*k%p;
        ans=(ans+s*qz[i-1]%p*hz[i+1]%p)%p;
    }
    ans=ans*s1%p;
    write(ans),putchar('\n');
    return 0;
}
posted @ 2020-07-31 21:05  GK0328  阅读(129)  评论(0编辑  收藏  举报