牛客多校Round 4

Soved:3

rank:133

A.Ternay String

欧拉降幂一下 但是反复求phi会超时 但mod是同一个就可以记忆化一下

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;

char s[100005];
int len;
map<ll, ll> mp;

ll getphi(ll o)
{
    if(mp[o]) return mp[o];
    ll res = o;
    ll n = o;
    for(ll i = 2; i * i <= n; i++)
    {
        if(n % i == 0)
        {
            res -= res / i;
            while(n % i == 0) n /= i;
        }
    }
    if(n > 1)  res -= res / n;
    mp[o] = res;
    return res;
}

ll pow_mod(ll x, ll y, ll mo)
{
    ll res = 1;
    while(y)
    {
        if(y & 1) res = res * x % mo;
        y >>= 1;
        x = x * x % mo;
    }
    return res;
}

ll dfs(ll x, ll m)
{
    if(x < 0) return 0;
    if(m == 1) return 0;
    if(s[x] == '2')
    {
        ll p = getphi(m);
        ll tmp = (dfs(x - 1, p) + p) % p;
        tmp = pow_mod(2, tmp, m);
        return (6LL * tmp % m - 3LL + m) % m;
    }
    if(s[x] == '0') return (dfs(x - 1, m) + 1LL) % m;
    if(s[x] == '1') return (dfs(x - 1, m) * 2LL + 2LL) % m;
    return 0;
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%s", s);
        len = strlen(s);
        ll ans = dfs(len - 1, mod);
        printf("%lld
", ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/lwqq3/p/9383298.html