牛客网暑期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.
示例1
输入

3
000
012
22
输出

3
93
45

题意:一个串内只含有0,1,2三种数字.时间从0开始,每过一秒,字符串中所有1的后面会插入一个0,每个2后面会插入一个1,然后字符串的第一个数字被删除,询问多少秒后字符串为空串?(结果对1e9+7取模,若是不可能输出-1)。

思路:首先很显然,不会有消不完的情况,所以不会有-1。

           然后可以利用dp的思想取考虑。

           设dp[i]表示消去前i个数及其产生的所有数字所需要的时间。

           1,当a[i]=0,dp[i]=dp[i-1]+1。显然

           2,当a[i]=1,dp[i]=2*dp[i-1]+2。前面花了dp[i-1],产生dp[i-1]个0加上1本身和这一步产生的一个0。

           3,当a[i]=2,d[i]=3*(2^(dp[i-1]+1)-1)。打表推公式。。。。官方题解这么说的,直接推我反正不会

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
map<ll,ll> m;
 
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 quick_pow(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;
}
char s[100005];
 
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*quick_pow(2,dfs(i-1,m[mod])+1,mod)-3)%mod+mod)%mod;
    else return (2*dfs(i-1,mod)+2)%mod;
}
int main()
{
    ll i=1e9+7;
    for(; i != 1; i = m[i])
        m[i] = PH(i);
    m[1]=1;
    int T;
    scanf("%d",&T);
    while(T--)
    {
        cin>>s+1;
        int n=strlen(s+1);
        printf("%lld\n",dfs(n,1000000007));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/snayf/article/details/81275715