牛客多校第四场A ternary string ----推公式和指数循环节

链接:https://www.nowcoder.com/acm/contest/142/A
来源:牛客网

Ternary String
时间限制:C/C++ 4秒,其他语言8秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld
题目描述
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 become11021” 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

操作分析:
1、遇到0,直接删除,操作次数+1
2、遇到1,考虑之前已经操作了x次,那么这个1后面已经多生出了x个0,这个时候需要在经过x + 2次操作才能删完
3、遇到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)),以此类推
另外考虑到若干次后,mod一定是一个2的倍数,可以提前算好答案,来优化。
嗨,主要是推公式很难推出来!!!!

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 100005;
char s[N];
LL phi[35]={1000000007,1000000006,500000002,//3
243900800,79872000,19660800,5242880,2097152,//5
1048576,524288,262144,131072,65536,32768,16384,//7
8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1,1};//13
LL pow_mod(LL n,LL m,LL p)
{
    LL x = n;
    LL sum = 1;
    while(m)
    {
        if(m & 1)
            sum = (sum * x) % p;
        m >>= 1;
        x = (x * x) % p;
    }
    return sum;
}
LL dfs(int pos,int num)
{
    if(num > 27) return 0;
    if(pos == -1) return 0;
    if(s[pos] == '0'){
        return (dfs(pos - 1,num) + 1LL) % phi[num];
    }
    else if(s[pos] == '1'){
        return (dfs(pos - 1,num) * 2LL + 2LL) % phi[num];
    }else{
        //后面加+phi[num]) % phi[num]是为了防止出现负数 
        return (((3LL * pow_mod(2,dfs(pos - 1,num + 1) + 1,phi[num])) - 3LL) % phi[num] + phi[num]) % phi[num];
    }
}
int main()
{
    int t;
    while(~scanf("%d",&t))
    {
        while(t--)
        {
            scanf("%s",s);
            int len = strlen(s);
            printf("%lld\n",dfs(len - 1,0));
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36386435/article/details/81315376