题目

LOJ #152. 乘法逆元 2

题解

一个奇技淫巧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);
}

随机推荐

  1. ApplicaitionContext妙用request解耦合

    本文记录一个web应用中,如果要获取request对象怎么获取,本次主要思考来自看到上次文件必须把request对象放进service层导致的疑问,然后学习总结之. 第一,也是我们最常用的,在cont ...

  2. Tensorflow一些常用基本概念与函数(1)

    为了快速的熟悉TensorFlow编程,下面从一段简单的代码开始: import tensorflow as tf #定义‘符号’变量,也称为占位符 a = tf.placeholder(" ...

  3. 文文---Set,Map

    Set和Map Set:类似数组 成员的值是唯一的 下有 add(),has(),delete(),clear(),size 等方法 Map:类似于对象 成员的值是唯一的 下有 set(),has() ...

  4. ASP.NET Core ResponseCaching:基于 VaryByHeader 定制缓存 Key

    ASP.NET Core ResponseCaching 提供了缓存http响应内容的能力,通过它可以在本地内存中直接缓存http响应内容,这是速度最快的服务端缓存,省却了网络传输与生成响应内容的开销 ...

  5. hdu 1045

    http://acm.hdu.edu.cn/showproblem.php?pid=1045 Fire Net Time Limit: 2000/1000 MS (Java/Others)    Me ...

  6. Golang覆盖写入文件的小坑

    记录一点Golang文件操作的笔记,环境:Ubuntu // 删除文件 func removeFile() { err := os.Remove("test.txt") if er ...

  7. websocket作用

    1.即时通讯 web即时通讯(网页的QQ,聊天系统等)可以通过websocket实现. 2.轮询 web开发中,有时需要通过轮询(比如时间间隔5秒)去服务器读取数据. 使用HTTP协议向服务器发送re ...

  8. [转贴] 软件测试职业发展的 A 面和 B 面

    [转贴] 软件测试职业发展的 A 面和 B 面 1.所谓的软件测试技术到底包含什么? 梅子:我先来从传统意义上来谈一下测试技术,主要就是测试分析,测试设计,测试管理,测试执行,自动化测试技术,专项测试 ...

  9. PHP中array_merge和array+array的区别

    在PHP中可以使用array_merge函数和两个数组相加array+array的方式进行数组合并,但两者效果并不相同,区别如下: 当下标为数值时,array_merge()不会覆盖掉原来的值,但ar ...

  10. 110A

    #include <stdio.h> #include<string.h> #define MAXSIZE 30 int main() { char digits[30]; m ...