牛客网暑期ACM多校训练营(第三场): A. 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).

输入描述:

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.

输入

3
000
012
22

输出

3
93
45

 

有道处理方法一样的题:https://blog.csdn.net/Jaihk662/article/details/77927831

引用官方题解:

牛客网暑期ACM多校训练营(第三场): A. Ternary String(欧拉降幂+递推)_第1张图片

 

#include
#include
#include
#include
using namespace std;
#define LL long long
map p;
char str[2000005];
LL Euler(LL x)
{
	LL i, ans;
	if(x==1)
		return 1;
	ans = x;
	for(i=2;i*i<=x;i++)
	{
		if(x%i==0)
			ans = ans/i*(i-1);
		while(x%i==0)
			x /= i;
	}
	if(x!=1)
		ans = ans/x*(x-1);
	return ans;
}
LL Pow(LL a, LL b, LL mod)
{
	LL ans;
	ans = 1;
	while(b)
	{
		if(b%2)
			ans = ans*a%mod;
		a = a*a%mod;
		b /= 2;
	}
	return ans;
}
LL Jud(LL loc, LL mod)
{
	if(loc==0)
		return 0;
	if(str[loc]=='0')
		return (Jud(loc-1, mod)+1)%mod;
	if(str[loc]=='1')
		return 2*(Jud(loc-1, mod)+1)%mod;
	return (3*Pow(2, Jud(loc-1, p[mod])+1, mod)+mod-3)%mod;
}
int main(void)
{
	LL T, now, n;
	now = 1000000007;
	p[1] = 1;
	while(now!=1)
	{
		p[now] = Euler(now);
		now = p[now];
	}
	scanf("%lld", &T);
	while(T--)
	{
		scanf("%s", str+1);
		n = strlen(str+1);
		printf("%lld\n", Jud(n, 1000000007));
	}
	return 0;
}

 

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