uva 417 - Word Index(数位dp)

题目连接:uva 417 - Word Index

题目大意:按照题目中的要求,为字符串编号,现在给出字符串,问说编号为多少,注意字符串必须为递增的,否则编号为0。

解题思路:其实就是算说比给定字符串小并且满足递增的串由多少个。dp[i][j]表示第i个位为j满足比给定字符串小并且满足递增的串。
dp[i][j]=k=0j1dp[i1][k].
注意每次要处理边界的情况,并且最后要加上自身串。并且在处理边界的时候dp[i][0]要被赋值为1,代表前i个为空的情况。

#include <cstdio>
#include <cstring>
#include <algorithm>

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;
}

你可能感兴趣的:(uva 417 - Word Index(数位dp))