codeforces 1312E. Array Shrinking(区间DP)

Subject link: https://codeforces.com/problemset/problem/1312/E

Solution: From the meaning of the question, it can be seen that if a section of intervals can be merged, the last value is num[i][j]=k. If k!=0 means that the intervals [i,j] can be merged into k, preprocessing num[i ][j], and then enumerate i to update the value of dp[i].

#include <bits/stdc++.h>
using namespace std;
const int maxn=550;
int n,a[maxn];
int num[maxn][maxn],dp[maxn];


int main() {
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",a+i),num[i][i]=a[i];
	
	for(int l=1;l<=n;l++){
		for(int i=1;i+l<=n;i++){
			int j=i+l;
			for(int k=i;k<j;k++){
				if(num[i][k]==num[k+1][j]&&num[i][k]>0){
					num[i][j]=num[i][k]+1;
				}
			}
		}
	}
	for(int i=1;i<=n;i++){
		dp[i]=dp[i-1]+1;
		for(int j=1;j<=i;j++)
			if(num[j][i]>0)
				dp[i]=min(dp[i],dp[j-1]+1);
	}
	printf("%d\n",dp[n]);
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_44132777/article/details/104867701