Ternary String (规律+欧拉降幂 )牛客

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).
题意: 有一串数字串s,只包含三个数字0,1,2,每过一分钟,先是每个2后面会产生一个1,每个1后面会产生一个0,然后串头第一个数字会消失,

问经过多少秒,整个串全部消失。
思路: https://www.cnblogs.com/dilthey/p/9411125.html 附上优秀题解

#include
using namespace std;
typedef long long ll;
const ll Mod=1e9+7;
int c[105];
map<ll,ll>mp;
string s;
ll phi(ll n)
{
	ll res=n;
	for(int i=2;i*i<=n;i++)
	{
		if(n%i==0)
		{
			res=res-res/i;
			while(n%i==0)
				n/=i;
		}
	}
	if(n>1)
		res=res-res/n;
	return res;
}

ll fpow(ll a,ll b,ll p)
{
	ll r=1,base=a%p;
	while(b)
	{
		if(b&1)
			r=r*base%p;
		base=base*base%p;
		b>>=1;
	}
	return r;
}

void init()
{
	ll x=Mod;
	while(x>1)
		x=mp[x]=phi(x);
	mp[1]=1;
}
ll solve(int i,ll p)
{
	if(i==-1)
		return 0;
	if(p==1)
		return 0;
	if(s[i]=='0') return (solve(i-1,p)+1+p)%p;
	if(s[i]=='1') return (2*solve(i-1,p)+2+p)%p;
	if(s[i]=='2') return (6*fpow(2,solve(i-1,mp[p]),p)-3+p)%p;
	return 0;
}

int main()
{
	init();
	int T;
	scanf("%d",&T);
	while(T--)
	{
		cin>>s;
		int len=s.size();
		printf("%lld\n",solve(len-1,Mod));
	}
	return 0;
}

你可能感兴趣的:(数论)