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

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
",count);
24     }
25     return 0;
26 } 

     

原文地址:https://www.cnblogs.com/yoke/p/6904472.html