「Luogu-P5431」【模板】乘法逆元2

给定$n$个正整数$a_i$,求出在$\bmod p$意义下$\sum\limits_{i=1}^{n}k^i\cdot a_i^{-1}$

$\texttt{Data Range:}1\leq n\leq 5\times 10^6,2\leq k

链接

题解

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;
typedef int ll;
typedef long long int li;
const ll MAXN=5e6+51;
char buf[1<<15],*st=buf,*ed=buf;
ll cnt,mod,k,res,cur;
ll prefix[MAXN],invp[MAXN],num[MAXN];
inline char gcx()
{
return st==ed&&(ed=(st=buf)+fread(buf,1,32768,stdin),ed==st)?0:*st++;
}
inline ll read()
{
register ll num=0,neg=1;
register char ch=gcx();
while(!isdigit(ch)&&ch!='-')
{
ch=gcx();
}
if(ch=='-')
{
neg=-1;
ch=gcx();
}
while(isdigit(ch))
{
num=(num<<3)+(num<<1)+(ch-'0');
ch=gcx();
}
return num*neg;
}
inline ll qpow(ll base,ll exponent)
{
ll res=1;
while(exponent)
{
if(exponent&1)
{
res=(li)res*base%mod;
}
base=(li)base*base%mod,exponent>>=1;
}
return res;
}
int main()
{
cnt=read(),mod=read(),k=read(),prefix[0]=1;
for(register int i=1;i<=cnt;i++)
{
prefix[i]=1ll*prefix[i-1]*(num[i]=read())%mod;
}
invp[cnt]=qpow(prefix[cnt],mod-2);
for(register int i=cnt-1;i;i--)
{
invp[i]=1ll*invp[i+1]*num[i+1]%mod;
}
res=(res+1ll*k*invp[1]%mod)%mod,cur=1ll*k*k%mod;
for(register int i=2;i<=cnt;i++)
{
res=(res+1ll*cur*invp[i]%mod*prefix[i-1]%mod)%mod;
cur=1ll*cur*k%mod;
}
printf("%d\n",res);
}