Codeforces 805D Minimum number of steps

xiaoxiao2021-02-28  142

题意:

          给出一个只含 a b 字符的串,问不断将串中的 “ab” 字串替换为 “bba” 至少需要几次可以结束替换,结果对 1e9 + 7 取余。

思路:

          首先,替换的顺序并不影响最终替换的次数。

          我们从空串开始模拟添加,可以发现规律,每加入一个 ‘b’ ,设 ‘b’ 之前 ‘a’ 的个数为 x ,替换次数就加上 2^x -1

          例子:             ab 1

                                  aab 3

                                  abab 4 = 1 + 3

                                  ababab 11 = 1 + 3 + 7

          由此将整个串扫一遍即可。

代码:

#include <bits/stdc++.h> using namespace std; const int MOD=1e9+7; const int MAXN=1e6+100; long long m[MAXN]; int main() { m[0]=1; for(int i=1;i<MAXN-1;i++) m[i]=(m[i-1]*2)%MOD; for(int i=0;i<MAXN-1;i++) m[i]--; string str; while(cin>>str){ int n=str.size(); int cut=0; long long ans=0; for(int i=0;i<n;i++){ if(str[i]=='a'){ cut++; }else{ ans+=m[cut]; ans%=MOD; } } cout<<ans<<endl; } }

转载请注明原文地址: https://www.6miu.com/read-17592.html

最新回复(0)