列表

详情


NC17337. 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

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++11(clang++ 3.9) 解法, 执行用时: 579ms, 内存消耗: 6104K, 提交时间: 2018-07-30 10:08:24

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
map<ll,ll> m;
	string s;
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--){
		cin>>s;
		s="1"+s;
		int len=s.length();
		printf("%lld\n",dfs(len-1,1000000007));
	}
	return 0;
}

Python3(3.5.2) 解法, 执行用时: 2004ms, 内存消耗: 4708K, 提交时间: 2018-07-28 20:08:28

def Mod(x, y):
    return x if x < y else x % y + y
gao = [1000000007, 1000000006, 500000002, 243900800, 79872000, 19660800, 5242880]
i = 1 << 21
while i >= 2:
    gao.append(i)
    i >>= 1
def gen(i):
    return gao[i] if i < 28 else 1
for _ in range(int(input())):
    s = input()
    n = 0
    p = 0
    for x in s:
        if x == '2':
            p += 1
    for x in s:
        if x == '0':
            n = (n + 1) % gen(p)
        elif x == '1':
            n = 2 * (n + 1) % gen(p)
        else:
            p -= 1
            mod = gen(p)
            n = (3 * pow(2, Mod(n + 1, gen(p + 1)), mod) - 3) % mod
    print(n)

上一题