题解:P17118 [Algo Beat 009 & MROI-R1] ERESHKIGAL
前言
这题代码调了我一个下午喵,哭死(常数优化真是个玄学)。
前置知识
Pollard-Rho 算法,阶。
Solution
化简
我们先考虑
显然
其中
由
从而
求式子
不难知
由于
code
代码喵!
/*
注意:两个范围为 ull 的数相加要加 __int128,相乘要加 __uint128_t。
别想用龟速乘,因为我 T 了很多遍。
*/
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
#define u12 __uint128_t
constexpr int mod = 1e9 + 7;
int pr[12] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
vector<int> p;
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
int ksm(int a, int b, int p) {
int ans = 1;
while(b) {
if(b & 1) ans = (u12)ans * a % p;
b >>= 1, a = (u12)a * a % p;
}
return ans;
}
bool MR(int a, int n) {
if(n < 3 || n % 2 == 0) return (n == 2);
int d = n - 1, r = 0;
while(!(d & 1)) d >>= 1, ++r;
int t = ksm(a, d, n);
if(t == 1) return 1;
for(int i = 0; i < r; ++i) {
if(t == n - 1) return 1;
t = (u12)t * t % n;
}
return 0;
}
bool prime(int n) {
if(n <= 1) return 0;
for(int i = 0; i <= 11; ++i) {
if(n == pr[i]) return 1;
if(n % pr[i] == 0) return 0;
if(!MR(pr[i], n)) return 0;
}
return 1;
}
int Pollard_Rho(int n) {
static mt19937_64 sj(chrono::steady_clock::now().time_since_epoch().count());
uniform_int_distribution<int> u(1, n - 1);
int c = u(sj);
auto f = [&](int x) { return ((u12)x * x % n + c) % n; };
int x = 0, y = 0, s = 1;
for (int k = 1; ; k <<= 1, y = x, s = 1) {
for (int i = 1; i <= k; i ++) {
x = f(x); s = (u12)s * (x > y ? x - y : y - x) % n;
if (i % 127 == 0) {
int d = gcd(s, n);
if (d > 1) return d;
}
}
int d = gcd(s, n);
if (d > 1) return d;
}
return n;
}
void work(int n) {
if (n <= 1) return ;
if (n == 4) return p.push_back(2ll), void();
if (prime(n)) return p.push_back(n), void();
int x = n;
while (x == n) x = Pollard_Rho(n);
work(x); work(n / x);
}
int phi(int n) {
work(n);
sort(p.begin(), p.end());
auto pos = unique(p.begin(), p.end());
p.erase(pos, p.end());
int ans = n;
for(int P : p) ans = ans / P * (P - 1);
return ans;
}
int delta(int n) {
int x = phi(n), ans = 1;
p.clear(), work(x);
sort(p.begin(), p.end());
auto pos = unique(p.begin(), p.end());
p.erase(pos, p.end());
for(int P : p)
while(!(x % P) && ksm(2, x / P, n) == 1)
x /= P;
return x;
}
int calc(int n) {
int m = delta(n);
return (u12)(ksm(2, m, mod) + mod - 1) % mod * ksm(n % mod, mod - 2, mod) % mod * (__int128)(n + mod - 2) % mod;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
cout << calc(n) << '\n';
return 0;
}
有错误欢迎在下面指出喵!
如果你为错过太阳而流泪,那你也将错过群星。