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

博客介绍了如何利用欧拉降幂和快速幂算法解决一个关于ternary字符串自我复制的问题。在每秒的复制过程中,0、1、2分别触发不同的变化,目标是计算字符串变为空字符串所需的最少步数,模(10^9 + 7)后的结果。文章提供了官方解答,强调了在处理过程中需要递归计算欧拉函数的阶,并使用欧拉降幂公式进行优化。

题目链接

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;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值