Minimum number of steps 805D

本文解析了CodeForces竞赛中一道关于字符串操作的问题。通过分析题目要求,给出了高效的求解算法,即如何将字符串中的ab替换为bba,并计算最少的操作次数。文章提供了一个C++实现示例,详细展示了算法步骤。

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

http://codeforces.com/contest/805/problem/D

 

 

D. 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 modulo109 + 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 from1 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".

 

题意:将字符串中ab 替换成 bba 进行多少次操作字符串中没有 ab

分析:将字符ab 替换成 bba 可以看成 a 向右移动一位, ab 中的 b 后增加一个 b

    每次将a 字符移动到所有b字符 的右端, 下一个a右边的b就多了一倍, 所以每遇到一个a 加上右边的b,然后更新右边的b为2*b

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 
 5 const ll mod = 1e9 + 7;
 6 // "ab" ?→? "bba".
 7 // "aab" ?→? "abba" ?→? "bbaba"?→? "bbbbaa".
 8 
 9 int main(){
10     string str;
11     while(cin >> str){
12         //cout << str << endl;
13         ll b = 0;
14         ll ans = 0;
15         for(ll i = str.length() - 1; i >= 0; i--){
16             // cout << "b " << b<< endl;
17             if(str[i] == 'b')
18                 b++;
19             //cout << "b " << b<< endl;
20             if(str[i] == 'a'){
21                 ans += b%mod;
22                 //cout << ans << endl;
23                 ans %= mod;
24                 b *= 2;
25                 b %= mod;
26             }
27         }
28         cout << ans% mod << endl;
29     }
30 }

 

 

 

转载于:https://www.cnblogs.com/jxust-jiege666/p/6822763.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值