题解:P5431 【模板】模意义下的乘法逆元 2
前置知识:
提供一种与其他题解不同的做法。
思路
对题中式子进行推导,可得到:
不妨设
现在考虑如何求
注意到
设
边界条件是
复杂度
输入、求
分治过程的复杂度为
最后求
总复杂度为
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int M = 5001000;
int n , p , k , a[M] , ans;
int qpow(int x , int y){
int res = 1;
while(y){
if(y & 1) res = res * x % p;
x = x * x % p , y >>= 1;
}
return res;
}
pair<int , int> solve(int l , int r){
if(l == r) return make_pair(1 , a[l]);
int mid = (l + r) >> 1;
auto x = solve(l , mid) , y = solve(mid + 1 , r);
return make_pair((x.first * y.second + x.second * y.first) % p , x.second * y.second % p);
}
signed main(){
ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0);
cin>>n>>p>>k;
for(int i = 1; i <= n; ++i) cin>>a[i];
for(int i = n , x = 1; i; --i , (x *= k) %= p) (a[i] *= x) %= p;
auto pr = solve(1 , n);
cout<<(pr.first * qpow(pr.second , p - 2) % p * qpow(k , n) % p)<<'\n';
}
solve(l,r) 函数返回值的 first 对应 second 对应