2021牛客寒假算法基础集训营1 A
2021牛客寒假算法基础集训营1 A
题目链接:https://ac.nowcoder.com/acm/contest/9981/A
题目大意
长度不超过\(n\),且包含子序列“\(us\)”的、只由小写字母构成的字符串有多少个? 答案对\(10^9+7\)取模。
所谓子序列,指一个字符串删除部分字符(也可以不删)得到的字符串。
例如,"unoacscc"包含子序列"us",但"scscucu"则不包含子序列"us"
思路
DP思路,求串dp[i]长度为i时,有us的串的数量
分为两种情况
1.前i-1个字符有us 那么第i个字符可以是任意字符 即dp[i-1]*26
2.前i-1个字符中有u但没有us,且第i个字符为s
前i-1个字符总共有26^(i-1)种可能
前i-1个字符且不含有u总共有25^(i-1)种可能
所以前i-1个字符有u总共有26^(i-1) - 25^(i-1)种可能
有u又没有us则有26^(i-1) - 25^(i-1) - dp[i-1]种可能
那么把1和2加起来就是26^(i-1) - 25^(i-1) + 25*dp[i-1]种可能
要注意的一点是取模之后减法可能会减出负数,要+MOD来避免出错
Code
#include<string>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define LL long long
#define MOD 1000000007
#define MAXN 100050
#define register long long
#define PI 3.1415926
LL read()
{
LL w = 1, x = 0;
char ch = 0;
while (ch < '0' || ch>'9')
{
if (ch == '-')
w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = x * 10 + (ch - '0');
ch = getchar();
}
return w * x;
}
LL quickpow(LL x,LL y,LL m)//二分思想
{
x=x%m;//防止第一个x*x就爆掉longlong
LL ans=1;//记录答案
while(y)// 注意如果y=0的话不会进入循环
{
if(y&1)//判断y是否是单数
{
ans=ans*x;
ans=ans%m;
}
x=x*x;
x=x%m;
y=y>>1;
}
ans=ans%m;//防止出现特殊数据:1^0%1=0的情况
return ans;
}
LL n,dp[1000005],s;
int main()
{
n=read();
dp[1]=0;
dp[2]=1;
for(register int i=2;i<=n;i++)
{
dp[i]=dp[i-1]*25+quickpow(26,i-1,MOD)-quickpow(25,i-1,MOD)+MOD;//这里加MOD是为了防止前面取模的减法出现负数的情况!
dp[i]%=MOD;
s+=dp[i];
s%=MOD;
}
cout<<s<<endl;
return 0;
}