牛客网暑期acm多校训练第4场A题——欧拉降幂+快速幂模板

题目链接

A ternary string is a sequence of digits, where each digit is either 0, 1, or 2.
Chiaki has a ternary string s which can self-reproduce. Every second, a digit 0 is inserted after every 1 in the string, and then a digit 1 is inserted after every 2 in the string, and finally the first character will disappear.
For example, ``212'' will become ``11021'' after one second, and become ``01002110'' after another second.
Chiaki would like to know the number of seconds needed until the string become an empty string. As the answer could be very large, she only needs the answer modulo (109 + 7).

输入描述:

There are multiple test cases. The first line of input is an integer T indicates the number of test cases. For each test case:
The first line contains a ternary string s (1 ≤ |s| ≤ 105).
It is guaranteed that the sum of all |s| does not exceed 2 x 106.

输出描述:

For each test case, output an integer denoting the answer. If the string never becomes empty, output -1 instead.

示例1

输入

3
000
012
22

输出

3
93
45

官方解答:

遇到0,直接删除,操作次数+1

遇到1,考虑之前已经操作了了x次,那么这个1后⾯面已经多⽣生出了了x个0。这个时 候需要再经过x+2次操作才能删完

遇到2,考虑之前已经操作了了x次,然后打个表可以发现,之后还需要经过3 * (2 ^ (x + 1) - 1) - x次操作才能全部删完

可见需要计算a*2^x mod (10^9 + 7),于是也得计算x mod phi(10^9+7),考虑到x 可能也是之前某些2^x的组合,因此还得算x mod phi(phi(10^9+7)),依次类推, phi(phi(phi(10^9+7))), …, phi^k(10^9+7)都得计算。

用到欧拉降幂公式来优化 

欧拉降幂:a^{x}\equiv a^{x \mod \varphi (p)+\varphi(p)}( mod\ p) (x\geq p)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
map<ll,ll> m;
const int MOD=1e9+7;
const int maxn=1e5+7;
char s[maxn];

ll ph(ll x)//欧拉降幂
{
    ll res=x,a=x;
    for(ll i=2;i*i<=x;i++)
    {
        if(a%i==0)
        {
            res=res/i*(i-1);
            while(a%i==0) a/=i;
        }
    }
    if(a>1) res=res/a*(a-1);
    return res;
}
ll poww(ll a,ll b,ll mod)//快速幂
{
    ll ans=1;
    while(b)
    {
        if(b&1) ans=(ans*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return ans;
}
ll dfs(ll i,ll mod)
{
    if(i==0) return 0;
    else if(s[i]=='0') return (dfs(i-1,mod)+1)%mod;
    else if(s[i]=='2') return ((3ll*poww(2,dfs( i-1,m[mod])+1,mod)-3)%mod+mod)%mod;
    else return (2*dfs(i-1,mod)+2)%mod;
}
int main()
{
    ll t,i=1000000007;
    cin>>t;
    for(;i!=1;i=m[i])
        m[i]=ph(i);
    m[1]=1;
    while(t--)
    {
        scanf("%s",s+1);
        cout<<dfs(strlen(s+1),MOD)<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/codetypeman/article/details/81327108