HDU 4055 Number String(dp)

dp[i][j]表示i个数,结尾是j的种数,对于多一个数字,如果要增加dp[i][j] = sigma{dp[i - 1][k]} {k < j},反之dp[i][j] = sigma{dp[i - 1][k]} (k > j),实际转移过程只需要循环一遍,不断记录前缀和即可

代码:

#include 
#include 
#include 
using namespace std;

const int N = 1005;
const int MOD = 1000000007;

char str[N];
int dp[N][N];

int main() {
    while (~scanf("%s", str + 2)) {
        int n = strlen(str + 2) + 1;
        memset(dp, 0, sizeof(dp));
        dp[1][1] = 1;
        for (int i = 2; i <= n; i++) {
            int sum = 0;
            if (str[i] == 'I' || str[i] == '?') {
                for (int j = 1; j <= i; j++) {
                    dp[i][j] = (dp[i][j] + sum) % MOD;
                    sum = (sum + dp[i - 1][j]) % MOD;
                }
            }
            sum = 0;
            if (str[i] == 'D' || str[i] == '?') {
                for (int j = i; j >= 1; j--) {
                    dp[i][j] = (dp[i][j] + sum) % MOD;
                    sum = (sum + dp[i - 1][j - 1]) % MOD;
                }
            }
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) ans = (ans + dp[n][i]) % MOD;
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(高效算法-动态规划)