$O(n+log(mod))$求乘法逆元的方法
题目
题解
一个奇技淫巧qwq。可以离线求乘法逆元,效率\(O(n+log(mod))\)。
考虑处理出\(s_n\)表示\(\prod_{i=1}^na_i\)。以及\(sinv_n\)表示\(\prod_{i=1}^na_i\)的逆元。
那么对于每次询问,\(sinv_i*s_{i-1}\)就是答案。
\(s_i\)显然可以在输入的时候顺便处理出来,\(sinv_n=(s_n)^{mod-2}\)(如果\(mod\)不是质数就exgcd一下)。
对于\(sinv_i(i\not = n)\),显然有\(sinv_i=sinv_{i+1}*a_{i+1}\)。则可以\(O(n+log(mod))\)求出来\(sinv_i\)。
总复杂度是\(O(n+log(mod))\)的
#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define il inline
namespace io {
#define in(a) a = read()
#define out(a) write(a)
#define outn(a) out(a), putchar('\n')
#define I_int ll
inline I_int read() {
I_int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x * f;
}
char F[200];
inline void write(I_int x) {
if (x == 0) return (void) (putchar('0'));
I_int tmp = x > 0 ? x : -x;
if (x < 0) putchar('-');
int cnt = 0;
while (tmp > 0) {
F[cnt++] = tmp % 10 + '0';
tmp /= 10;
}
while (cnt > 0) putchar(F[--cnt]);
}
#undef I_int
}
using namespace io;
using namespace std;
#define N 5000010
const ll mod = 1e9 + 7;
int n = read();
ll sinv[N], a[N], s[N];
ll power(ll a, ll b) { ll ans = 1;
while(b) {
if(b & 1) ans = ans * a % mod;
a = a * a % mod; b >>= 1;
} return ans;
}
int main() { s[0] = 1;
for(int i = 1; i <= n; ++i) {
a[i] = read();
s[i] = s[i - 1] * a[i] % mod;
} ll ans = 0;
sinv[n] = power(s[n], mod - 2); sinv[0] = 1;
for(int i = n; i; --i) sinv[i - 1] = sinv[i] * a[i] % mod;
for(int i = 1; i <= n; ++i) {
ll inv = sinv[i] * s[i - 1] % mod;
ans = (ans * 998244353 + inv) % mod;
}
outn(ans);
}
随机推荐
- linux的基本操作(磁盘管理)
磁盘管理 [查看磁盘或者目录的容量 df 和 du] df 查看已挂载磁盘的总容量.使用容量.剩余容量等,可以不加任何参数,默认是按k为单位显示的 df常用参数有 –i -h -k –m等 -i 使用 ...
- Codeforces 1132 - A/B/C/D/E/F - (Undone)
链接:http://codeforces.com/contest/1132 A - Regular Bracket Sequence - [水] 题解:首先 "()" 这个的数量多 ...
- CodeForces 570D - Tree Requests - [DFS序+二分]
题目链接:https://codeforces.com/problemset/problem/570/D 题解: 这种题,基本上容易想到DFS序. 然后,我们如果再把所有节点分层存下来,那么显然可以根 ...
- Apktool反编译apk资源文件
Android开发过程中,如何查看已经打包的APK内部xml呢,google下找到了apktool这个工具, apktool项目现在已经迁移到了github:apktool 目前最新版本2.2.2,如 ...
- ES6语法(3)—— 用promise()对象优雅的解决异步操作
Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大. 所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果. ...
- 加壳工具-Virbox Protector Standalone
深思数盾自动保护工具Virbox Protector Standalone,是深思数盾科技股份有限公司经过多年技术深耕开发的一款高强度自动保护(加密)工具. 该工具集混淆.虚拟化.外壳加密.数据加密于 ...
- Python3.6安装使用tesserocr文件时遇到问题
本机运行环境: Win 10 version 1709; Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit ...
- workman项目设置开机自启动
https://blog.csdn.net/xxq929604980/article/details/78558317 http://man.linuxde.net/chkconfig 1.脚本编写 ...
- mongoose findByIdAndUpdate不执行的解决方法
请参考Mongoose的文档 1.findOneAndUpdate([query], [doc], [options], [callback]) 有callback传递才执行. 2.exec是prom ...
- 运行pytorch代码遇到的error解决办法
1.no CUDA-capable device is detected 首先考虑的是cuda的驱动问题,查看gpu显示是否正常,然后更新最新的cuda驱动: 第二个考虑的是cuda设备的默认参数是否 ...