Codeforces Round #411 (Div. 2) D. Minimum number of steps

针对只包含'a'和'b'的字符串,通过将所有'ab'子串替换为'bba',直至不再存在'ab'子串的过程,本文提供了一种高效算法来计算所需的最小步骤数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D. Minimum number of steps
time limit per test  1 second
memory limit per test  256 megabytes
 

We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.

The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

Input

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Output

Print the minimum number of steps modulo 109 + 7.

 
input
ab
output
1
input
aab
output
3
Note:

The first example: "ab"  →  "bba".

The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

 

题目大意:

     输入一个只包含’a‘  ’b‘的字符串,将该字符串中的’ab‘换成’bba‘,直到字符串中不出现’ab',问最小需要多少步。

解题思路:

     要想不出现ab的情况,则字符串中所有的a字符都在b字符的右边,所以要做的就是把所有的a字符向右移动

     ab--->bba可以看作是把a和b调换位置然后b的数量增加两倍

     所以ab--->bba  需要1步    abb--->bbbba 需要2步 .......

     所以我们可以在字符串中从后往前判断a字符后面有多少个b字符,然后根据上面找到的规律判断步数即可

 

AC代码:

 1 #include <stdio.h>
 2 #include <string.h> 
 3 #define mod 1000000007
 4 int main ()
 5 {
 6     char str[1000010];
 7     int i;
 8     while (~scanf("%s",str))
 9     {
10         int count = 0,sum = 0;
11         int len = strlen(str);
12         for (i = len-1; i >= 0; i --)
13         {
14             if (str[i] == 'b')   // 记录b字符的个数 
15                 sum ++;
16             else
17             {
18                 count = (count+sum)%mod;   // 跟新步数 
19                 sum *= 2;                  // b字符的数量翻倍 
20                 sum %= mod;            // 预防sum超出范围 
21             }
22         }
23         printf("%d\n",count);
24     }
25     return 0;
26 } 

 

     

转载于:https://www.cnblogs.com/yoke/p/6904472.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值