区间dp
比如从i到j如果str[i] == str[j]那么i到j的值就与i+1到j-1相同,否则从i到j-1与i+1到j中选一个最优解,这道题直接定义int的二维数组会mle,用short,也可以用滚动数组。
#include<stdio.h> const int maxa = 5005; short dp[maxa][maxa]; char str[maxa]; #define min(a,b) a<b?a:b; int main(){ int n; while(scanf("%d", &n)!=EOF){ scanf("%s", str); for(int i = 1; i < n; i++){ for(int j = 0; j + i < n; j++){ if(str[j] == str[j+i]){ dp[j][j+i] = dp[j+1][j+i-1]; }else{ dp[j][j+i] = min(dp[j+1][j+i]+1, dp[j][j+i-1]+1); } } } printf("%d ", dp[0][n-1]); } }