inverse element
use
Since division cannot be modulo, there is such a thing as a multiplicative inverse
(a/b)%p is equivalent to finding a∗(b’s inverse)%p
Fermat's little theorem
Since the modulus p is always a prime number in algorithmic competitions, Fermat's little theorem can be used:
b^(p−1)%p=1
It can be directly obtained that b^(p-2) is the inverse element of b in the sense of mod p
ll pow(ll a, ll n, ll p) //快速幂 a^n % p
{
ll ans = 1;
while(n)
{
if(n & 1) ans = ans * a % p;
a = a * a % p;
n >>= 1;
}
return ans;
}
ll niyuan(ll a, ll p) //费马小定理求逆元
{
return pow(a, p - 2, p);
}
Extended Euclid
For using the extended Euclidean algorithm to find the inverse element, obviously, if bx%p=1, then bx+py=1 (p=0, solve x), directly use exgcd(b, p, x, y), Then (x%p+p)%p is the inverse of b ((x%p+p)%p is the smallest positive integer solution of x).
void exgcd(ll a, ll b, ll &x, ll &y) //拓展欧几里得算法
{
if(!b)
x = 1, y = 0;
else
{
exgcd(b, a % b, y, x);
y -= x * (a / b);
}
}
ll niyuan(ll a, ll b) //求a对b取模的逆元
{
ll x, y;
exgcd(a, b, x, y);
return (x + b) % b;
}
example
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define P 998244353
ll powmod(ll a,ll n, ll p)
{
ll ans=1;
while(n)
{
if(n&1)ans=ans*a%p;
a=a*a%p;
n>>=1;
}
return ans;
}
ll c[1000010];
ll f[1000010];
int main() {
ios::sync_with_stdio(0);
int n;
cin >> n;
for(int i=0;i<n;i++)
{
int k;
cin>>k;
for(int j=0;j<k;j++)
{
int e;
cin>>e;
c[e]++;
f[e]=(f[e]+powmod(n,P-2,P)%P*powmod(k,P-2,P)%P)%P;
}
}
ll ans=0;
for(int i=1;i<=1e6;i++)
{
ans=(ans+c[i]*f[i]%P*powmod(n,P-2,P)%P)%P;
}
cout<<ans<<endl;
return 0;
}
references
https://www.cnblogs.com/-citywall123/p/10673212.html