牛客网暑期ACM多校训练营(第四场)A Ternary String

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

题目描述

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

题意:给出一个字符串,每秒会在每个1后面插入一个0,每个2后面插入一个1,第一个字符会消失,问这个字符串会在第几秒全部消失。

 

 题解:

可以对每个字符单独考虑,计算这个字符在第k秒时,他和他的后代需要多少秒全部消失。

0这个字符是1s就会消失。

假设已经过了k秒,那么对于一个1,会花费k+2的时间。

对于一个2,打个表oeis一下,发现是3*2^n-n-2秒。这里n=k+1。

这个就要用扩展欧拉定理来计算,递归取模。

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
ll ans,q,ou[100005];
ll quick(ll a,ll k,ll p){
    ll ans=1;
    while(k){
        if(k&1)ans=ans*a%p;
        k/=2;
        a=a*a%p;
    }
    return ans;
}
ll euler(ll n){ 
     ll res=n,a=n;  
     for(ll i=2;i*i<=a;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;  
} 
char s[100005];
ll solve(ll t,ll lab){
	ll m=ou[lab];
	if(t==0)return 0;
	if(s[t]=='0')return (1+solve(t-1,lab))%m;
	if(s[t]=='1')return (solve(t-1,lab)*2+2)%m;
	if(s[t]=='2'){
		ll now=solve(t-1,lab+1);
		ll ans=now+(3*quick(2,now+1,m)-now-3);
		ans=ans%m;
		if(ans<0)ans+=m;
		if(ans>=m)ans-=m;
		return ans;
	}
	return 0;
}
void init(){
	ou[0]=mod;
	for(ll i=1;i<=100000;i++)ou[i]=euler(ou[i-1]);
}
int main(){
    int o;
    init();
    scanf("%d",&o);
    while(o--){
        ans=0;
        q=0;
        scanf("%s",s+1);
        ans=solve(strlen(s+1),0);
        printf("%lld\n",ans%mod);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值