Minimum number of steps

来源:互联网 发布:济南泉方pubmed数据库 编辑:程序博客网 时间:2024/04/30 18:41

B. Minimum number of steps
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.
Examples
Input

ab

Output

1

Input

aab

Output

3

#include <iostream>#include <algorithm>#include <cstdio>#include <list>#include <stack>#include <vector>#include <map>#include <set>#include <ostream>#include <cstring>#include <cmath>#include <string>#include <queue>#include <cstdlib>#include <sstream>#include <fstream>#include <iomanip>#define N 1000005#define INF (1 << 30)#define NIL -1const int mod = (int)1e9 + 7;using namespace std;char str[N];int tab[N];int main(){    int T, n, k;    tab[1] = 1;    tab[0] = 0;    for (int i = 2; i < N; ++i)    {        tab[i] = 2 * tab[i - 1] + 1;        tab[i] %= mod;    }    while (scanf("%s", str) != EOF)    {        int count_a = 0;        long long ans = 0;        for (int i = 0; str[i]; ++i)        {            if (str[i] == 'a')                ++count_a;            else            {                ans += tab[count_a];                ans %= mod;            }        }        printf("%d\n", ans);    }    return 0;}

经过一番分析,消去的实质是把位于a后面的b放到a的前面,而aab和aabb的情况(每次消去,a的个数不变),当想要消除更靠前的b时,后面的那个b可以先忽略,消除后就变成bbbbaab,位于a前面的b是可以忽略的,位于b后面的a也是可以忽略的,所以此时相当于aab,所以在step的数值上,aabb等于2 * aab,aabbb等于3 * aab。

下面推tab[]
aab->abba == 2 * ab
aaab->aabba == 2 * aab

->tab[i] = tab[i - 1] * 2 + 1;//tab[i]表示前面有i个a是消去一个b要的操作数。

0 0
原创粉丝点击