前置知识: 求单个数的逆元。
提供一种与其他题解不同的做法。
思路
对题中式子进行推导,可得到:
不妨设 ,,,则原式等于 。 现在考虑如何求 。 注意到 中的每一个求和项都形如 中除去 之后的乘积,则可按 在区间中点的两侧进行分治。 设 ,则:
边界条件是 。
复杂度
输入、求 均可以 完成。 分治过程的复杂度为 。 最后求 的复杂度为 ,求 的逆元复杂度为 。 总复杂度为 。
代码
#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 对应 。