HDU1243 反恐训练营(dp)

题目链接。

分析:

本题和最长公共子序列是相识的。关键是dp数组的定义,直接定义dp[2500][2500]

在网上查了一下。优化了下代码。

跑时156 AC代码如下:

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 2500

int dp[2][MAXN];

int main(){
    int n, len1, len2, i, j, now, pre;
    char s1[MAXN], s2[MAXN], s[MAXN];
    int point[30];

    while(scanf("%d", &n) == 1){
        scanf("%s", s);

        for(i=0; i<n; i++){
            scanf("%d", &point[s[i]-'a']);
        }

        scanf("%s%s", s1, s2);
        len1 = strlen(s1); len2=strlen(s2);

        memset(dp, 0, sizeof(dp));

        for(i=1; i<=len1; i++){
            now = i%2;
            pre = 1-now;
            for(j=1; j<=len2; j++){
                if(s1[i-1] == s2[j-1]){
                    dp[now][j] = dp[pre][j-1]+point[s2[j-1]-'a'];
                }
                else{
                    dp[now][j] = dp[pre][j] > dp[now][j-1] ? dp[pre][j] : dp[now][j-1];
                }
            }
        }

        printf("%d\n", dp[len1%2][len2]);
    }

    return 0;
}
原文地址:https://www.cnblogs.com/tanhehe/p/2945001.html