这里有一个由小写字母构成的字符串S . 小I是一个好(tao)奇(qi)的男孩,因此他想要找严格递增数字序列P(P_1到P_k)的数量,每个序列必须满足以下要求:
1. 1<=i<=k 时,S[P_i] = 'a'.
2. 1<=i<k 时 , 保证存在 整数 j ,j满足P_i<j<P_(i+1),而且s[j]='b'.
小I很烦恼(翻译题面的我也很烦恼,这翻译我尽力了) , 你帮帮他吧。 答案对1000000000 + 7 取余
Input
The first line contains the string s (s的长度不大于 10的5次方) consisting of lowercase Latin letters.
Output
In a single line print the answer to the problem ; — the number of such sequences P_1, P_2,……, P_k modulo 1000000000 + 7(1e9 + 7).
Examples
Input
abbaa
Output
5
Input
baaaa
Output
4
Input
agaa
Output
3
Note
In the first example, there are 5 possible sequences. [1], [4], [5], [1, 4],[1, 5].
In the second example, there are 4 possible sequences. [2], [3], [4], [5].
In the third example, there are 3 possible sequences. [1], [3], [4].
仅仅只是理解题意就理解了好久,我竟然连题意都理解不了
题意:一个字符串,遇到a要计数, 也可以选择任意一个在前面的a和一个在后面的a,这两个a之间必须有b
组合成ababa......的也行,只要挑选出的两个a之间有b就行。
方法一:
对于一组连续的a,把它和前面可能的总数进行组合,对于这一组连续的a,每一个a都可以选择和前面的组合,也可以全都不取
所以要乘上a的数量+1,最后由于不能所有的a都不取,所以答案-1
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
#define N 100010
#define mod 1000000007
using namespace std;
char a[N];
int main(){
while(scanf("%s",a)!=EOF){
ll ans=1,sum=0;
int n=strlen(a);
for(int i=0;i<n;i++){
if(a[i]=='a'){
sum++;
}else if(a[i]=='b'){
ans=(ans*(sum+1))%mod;
sum=0;
}
}
if(sum!=0)ans=(ans*(sum+1))%mod;
printf("%lld\n",ans-1);
}
return 0;
}
方法二:
简单DP
首先预处理字符串 S ,使得串中不存在除 a 、b 意外的字母且任意两个 b 不相邻,然后定义一个 last 变量存上一个 b 位置之前有多少序列,然后递推 dp:dp[ i ] = dp[ i - 1] + last + 1
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
char a[100005], s[100005];
ll dp[100005] = {0}, p = 0;
int main()
{
ll i;
scanf("%s", s + 1);
int len = strlen(s + 1);
a[p] = '*';
for(i = 1; i <= len; i++)
{
if(s[i] == 'a')a[++p] = s[i];
else if(s[i] == 'b' && a[p] != 'b')a[++p] = s[i];
}
ll last = 0;
for(i = 1; i <= p; i++)
{
if(a[i] == 'a')dp[i] = dp[i - 1] + last + 1;
else last = dp[i - 1], dp[i] = dp[i - 1];
dp[i] %= 1000000007;
}
printf("%lld\n", dp[p]);
return 0;
}