AT_abc300_e 题解

· · 题解

概率期望题先推式子。

很简单的,设 f(x) 为最终得到 x 的概率,f(n)=\frac{1}{6}\cdot (f(n)+f(\frac{n}{2})+f(\frac{n}{3})+f(\frac{n}{4})+f(\frac{n}{5})+f(\frac{n}{6})),n 不能整除就特判一下。

这时貌似进入了无限递归式,很简单,我们把 f(n) 移过去就行了,整理得到:f(n)=\frac{1}{5}\cdot (f(\frac{n}{2})+f(\frac{n}{3})+f(\frac{n}{4})+f(\frac{n}{5})+f(\frac{n}{6})),接着就有了暴力代码:(还需要算个逆元,另外边界 f(1)=1)

#include <iostream>
#define int long long
using namespace std;
const long long mod = 998244353;
long long n, inv;
long long q_pow (long long x, long long y) {
    if (y == 0) return 1;
    if (y & 1) return x * q_pow (x * x % mod, y >> 1) % mod;
    return q_pow (x * x % mod, y >> 1);
}
int f (long long x) {
    if (x == 1) return 1;
    int ret = 0;
    if (x % 2 == 0) ret += f (x / 2);
    if (x % 3 == 0) ret += f (x / 3);
    if (x % 4 == 0) ret += f (x / 4);
    if (x % 5 == 0) ret += f (x / 5);
    if (x % 6 == 0) ret += f (x / 6);
    return ret % mod * inv % mod;
}
signed main () {
    inv = q_pow (5, mod - 2);
    cin >> n;
    cout << f (n) % mod;
    return 0;
}

TLE 了咋办?凉拌炒鸡蛋好吃又好看加个记忆化就行了。遍历到的数字全部是 n 的因数,一个数的因数不可能太多,于是这题就解决了。

代码:

#include <map>
#include <iostream>
#define int long long
using namespace std;
const long long mod = 998244353;
long long n, inv;
map <int, int> m;
map <int, bool> u;
long long q_pow (long long x, long long y) {
    if (y == 0) return 1;
    if (y & 1) return x * q_pow (x * x % mod, y >> 1) % mod;
    return q_pow (x * x % mod, y >> 1);
}
int f (long long x) {
    if (u[x]) return m[x];
    u[x] = true;
    int ret = 0;
    if (x % 2 == 0) ret += f(x / 2);
    if (x % 3 == 0) ret += f (x / 3);
    if (x % 4 == 0) ret += f (x / 4);
    if (x % 5 == 0) ret += f (x / 5);
    if (x % 6 == 0) ret += f (x / 6);
    m[x] = ret % mod * inv % mod;
    return m[x];
}
signed main () {
    m[1] = 1;
    u[1] = true;
    inv = q_pow (5, mod - 2);//费马小定理计算逆元。
    cin >> n;
    cout << f (n);
    return 0;
}