CF607B
作者:互联网
区间dp 注意len==2的特判问题
1 #include<iostream> 2 #include<algorithm> 3 #include<cmath> 4 #include<cstdio> 5 #define INF 1e9 6 using namespace std; 7 const int maxn = 5e2 + 10; 8 int n; 9 int a[maxn]; 10 int dp[maxn][maxn]; 11 12 int main(){ 13 scanf("%d",&n); 14 for(int i = 1 ; i <= n ; i++){ 15 for(int j = i ; j <= n ; j++){ 16 dp[i][j] = INF; 17 } 18 } 19 for(int i = 1 ; i <= n ; i++){ 20 scanf("%d",&a[i]); 21 dp[i][i] = 1; 22 } 23 for(int i = 1 ; i < n ; i++){ 24 dp[i][i + 1] = a[i] == a[i + 1] ? 1 : 2; 25 }//若枚举len从2开始,dp[i+1][j-1]将无法被覆盖,因此需要特判 26 for(int len = 3 ; len <= n ; len++){ 27 for(int i = 1 ; i + len - 1 <= n ; i++){ 28 int j = i + len - 1; 29 for(int k = i ; k <= j - 1 ; k++){ 30 dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); 31 } 32 if(a[i] == a[j] && i + 1 <= j - 1) dp[i][j] = min(dp[i][j], dp[i + 1][j - 1]); 33 } 34 } 35 printf("%d\n",dp[1][n]); 36 37 return 0; 38 }
标签:10,int,特判,maxn,CF607B,include,dp 来源: https://www.cnblogs.com/ecustlegendn324/p/13797896.html