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 toperform some operations on it. On each step we choose one of substrings "ab" in thestring and replace it with the string "bba". If wehave no "ab" as a substring, our job is done. Print the minimumnumber of steps we should perform to make our job done modulo 109 + 7.
The string "ab" appearsas a substring if there is a letter 'b' right after the letter 'a' somewhere inthe string.
Input
The first line contains the initialstring consisting of letters 'a' and 'b' only withlength from 1 to 106.
Output
Print the minimum number of steps modulo 109 + 7.
Examples
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'为止。问最少的替换次数。
思路:替换后字符串肯定会变成'bbb...aaa...'的形式
同时可以写出几组样例进行观察
1.ab->bba
2.aab->bbbbaa
3.aaab->bbbbbbbbaaa
4.abb->bbbba
5.abbb->bbbbbba
观察可知,对于'aaa...bbb...'的形式,一个a后面的有多少b就要操作几次,而b前面有几个a就会使b的数目乘以2^n.
于是,我们可以选择从后面开始遍历(因为要把a一个个往后移),每碰到一个b,count加一,每碰到一个a,操作次数加上其后b的个数(即当前count的值),然后b的个数*2(count翻倍),过程中注意取模即可
#include <bits/stdc++.h>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define f(i,a,b) for(int i=(a);i<=(b);++i)
#define ll long long
const int maxn = 1e6+5;
const ll mod = 1e9+7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
#define rush() int T;scanf("%d",&T);while(T--)
char s[maxn];
int main()
{
ll cnt,ans;
while(~scanf("%s",s))
{
int len=strlen(s);
cnt=ans=0;
for(int i=len-1;i>=0;i--)
{
if(s[i]=='b')
{
cnt++;
}
else if(s[i]=='a')
{
ans+=cnt;
ans%=mod;
cnt*=2;
cnt%=mod;
}
}
printf("%I64d\n",ans);
}
return 0;
}