思路
首先是通过打表求出通项公式,结论是
设到当前位置经历了t秒
若当前位置为0,则消去0的时刻为t+1
若当前位置为1,则消去1及其产生的0的时刻为2*(t+1)
若当前位置为2,则消去2及其产生的0和1的时刻为3*(2^(t+1)-1)
由于指数非常大,所以简单的快速幂无法处理,需要用到拓展欧拉定理
源码
#include <bits/stdc++.h>
#define FastIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> PII;
const char sp = 32, cr = 10;
const ll inf = 0x3f3f3f3f;
const ll N = 1e5 + 5, M = 1e5;
const ll MOD = 1e9 + 7;
string str;
map<ll, ll> all;
ll phi(ll n) { //欧拉值
ll res = n;
for (ll i = 2;i * i <= n;++i) {
if (n % i == 0) {
res = res / i * (i - 1);
while (n % i == 0) n /= i;
}
}
if (n > 1) res = res / n * (n - 1);
return res;
}
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
void init(ll mod) { //预处理所有可能的欧拉值
while (mod != 1)
mod = all[mod] = phi(mod);
all[1] = 1;
}
ll pow_mod(ll a, ll b, ll p) {
// if (p == 0) cout << "p false" << cr;
if (gcd(a, p) == 1) //拓欧第一条
b %= p;
else {
if (b >= p) b = b % p + p; //拓欧第三条
}
ll res = 1;
while (b) {
if (b & 1) res = res * a % p;
a = a * a % p;
b >>= 1;
}
return res;
}
ll dfs(ll pos, ll mod) {
if (pos == -1) return 0;
// if (mod == 0) cout << "mod false";
if (str[pos] == '0') return (dfs(pos - 1, mod) + 1) % mod;
if (str[pos] == '1') return (2 * (dfs(pos - 1, mod)) + 2) % mod;
else return (3 * pow_mod(2, dfs(pos - 1, all[mod]) + 1, mod) - 3 + mod) % mod;
}
int main() {
FastIO;
init(MOD);
ll t;
cin >> t;
while (t--) {
cin >> str;
cout << dfs(str.length() - 1, MOD) << cr;
}
return 0;
}
问题与解决
Q1:快速幂已经能够保证指数的范围不会太大,那么为什么还要使用欧拉降幂?
A1:注意我们要求的最终问题是~2^x次方,这个x在从头到尾累计后是一个非常大的数字。我们使用递归来将这个指数拆开,如果直接使用快速幂那么指数确实不大,但是得到的答案确实错误的,因为(a^b^c)%mod != (a^(b^c%mod))%mod,可以试着这么写然后提交,得到的答案是错误的。而欧拉降幂就是解决这种通过递归将一个很大的指数拆开分层来求的的问题