P5431 乘法逆元2(逆元)

題目傳送門



時限: 550ms

思路: 按照這題數據範圍,我們一個一個去求a[i]的逆元,nlogp,對於這個時間顯然不夠,所以我們要換個方向思考。我們發現我們可以直接通分,分母直接變成了a[1]*a[2]*a[3]*a[4]…*a[n], 然後上面就是(i∈[1,n]) ki * a[1] * … * a[i-1] * a[i+1] * …* a[n],然後一開始預處理一下後綴乘積就行,最後算一個逆元就行。

#include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define endl '\n'
#define null NULL
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define pii pair<int,int>
#define ull unsigned long long
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
char *fs,*ft,buf[1<<20];
#define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++;
inline int read(){int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=gc();}
return x*f;}
using namespace std;
const int N=5e6+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-7;
const double PI=acos(-1);
int n,p,k;
ll qpow(ll a,ll b)
{
    ll res=1;
    while(b)
    {
        if(b&1)
            res=res*a%p;
        a=a*a%p;
        b>>=1;
    }
    return res;
}
int a[N],suf[N];
signed main()
{
    n=read();p=read();k=read();
    suf[n+1]=1;
    for(int i=1;i<=n;i++)
    {
        a[i]=read();
    }
    for(int i=n;i>=1;i--)
        suf[i]=suf[i+1]*a[i]%p;
    int m=k,pre=1,res=0;
    for(int i=1;i<=n;i++)
    {
        res=(res+(ll)m*pre%p*suf[i+1]%p)%p;
        pre=pre*a[i]%p;
        m=m*k%p;
    }
    res=res*qpow(suf[1],p-2)%p;
    printf("%lld\n",res);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章