CF1084C The Fair Nut and String(dp)

传送门


解题思路

概括一下题意:求字符串中abababa子序列的个数。
考虑dp。
设dp[i]表示以子序列第i位结尾的方案数。
显然第i位是'a'时dp[i]才不为0。
转移方程为:

\[dp[i]=1+\sum_{j=1}^k dp[j] \]

其中k为上一个b出现的位置。
显然可以边求dp边记录一个前缀和优化。
最后复杂度为O(n)。

当然还有更简单的递推式子。其实本质几乎一样,但是写起来简单。

AC代码

#include<iostream>
#include<cstdio>
template<class T>inline void print(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)print(x/10);
    putchar('0'+x%10);
}
const int mod=1e9+7;
char c;int ans,sum;
int main(){
	while(c=getchar()){
		if(c<'a'||c>'z') break;
		if(c=='a') ans=(ans+sum+1)%mod;
		if(c=='b') sum=ans;	
	}
	print(ans);
	return 0;
}
posted @ 2021-10-08 07:33  尹昱钦  阅读(49)  评论(2编辑  收藏  举报