Topic link: click here~
Topic
- How many strings consist of lowercase letters that are not more than n and contain the subsequence "us"? The answer is modulo 1e9+7.
- Subsequence, us may not be adjacent
- Range: 2≤n≤1e6
Ideas
- Use dp to transfer state. If you look at the mathematical formula to push the point here -
- Definition: dp[i][0] means a string of length i does not have u, dp[i][1] means a string of length i has u but no s, dp[i][2] means a string of length i There are us subsequences.
- Initialization: dp[1][0] = 25, dp[1][1] = 1, dp[1][2] = 0.
- State transition: dp[i][0] = dp[i-1][0] * 25 (there is no u before, and u is not selected in the current bit)
- dp[i][1] = dp[i-1][0] (there is no u before, the current position is u) + dp[i-1][1]*25 (u has been selected before but no s, currently Do not choose s)
- dp[i][2] = dp[i-1][1] (previously there is u but no s, the current position is s) + dp[i-1][2] * 26 (there is already us before, so currently Choose any)
- The length does not exceed n, so dp[i][2] all meet the requirements
ac code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int mod = 1e9 + 7;
const int maxn = 1e6 + 5;
ll dp[maxn][5];
int main(){
int n; cin >> n;
dp[1][0] = 25; //无u
dp[1][1] = 1; //有u无s
dp[1][2] = 0; //有us
ll ans = 0;
for(int i = 2; i <= n; i ++){
dp[i][0] = dp[i - 1][0] * 25 % mod;
dp[i][1] = (dp[i - 1][0] + dp[i - 1][1] * 25 % mod) % mod;
dp[i][2] = (dp[i - 1][1] + dp[i - 1][2] * 26 % mod) % mod;
ans = (ans + dp[i][2]) % mod;
}
cout << ans << endl;
return 0;
}