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

被折叠的 条评论
为什么被折叠?



