Question connection: Ultraviolet A 417-Word Index
According to the requirements in the question, it is a string number. Now we will give a string and ask how many strings are numbered. Note that the string must be incrementing; otherwise, the number is 0.
Solution: calculate the number of strings that are smaller than the given string and meet the increasing requirement. Dp [I] [j] indicates a string whose I-th position is j that is smaller than the given string and must be incremented.
Dp [I] [j] = Σ k = 0j? 1dp [I? 1] [k].
Pay attention to the situation of processing the boundary each time, and add its own strings at last. When processing the boundary, dp [I] [0] must be assigned a value of 1, which indicates that the first I is null.
#include
#include
#include using namespace std;const int N = 10;char str[N];int dp[N][3*N];int solve () { int len = strlen(str); if (len == 1) return str[0] - 'a' + 1;; for (int i = 1; i < len; i++) if (str[i] <= str[i-1]) return 0; int pre = str[0] - 'a' + 2; memset(dp, 0, sizeof(dp)); for (int i = 0; i + 'a' <= str[0]; i++) dp[1][i] = 1; for (int i = 1; i < len; i++) { for (int j = 0; j <= 26; j++) { for (int k = j+1; k <= 26; k++) dp[i+1][k] += dp[i][j]; } for (int j = pre; j + 'a' <= str[i]; j++) dp[i+1][j]++; pre = str[i] - 'a' + 2; dp[i+1][0]++; } int ans = 1; for (int i = 1; i <= 26; i++) ans += dp[len][i]; return ans;}int main () { while (scanf("%s", str) == 1) { printf("%d\n", solve()); } return 0;}