Interval dp principle

Interval DP

Stone merger

There are N piles of stones arranged in a row, their numbers are 1, 2, 3,...,N.

Each pile of stones has a certain mass, which can be described by an integer. Now we must combine these N piles of stones into one pile.

Only two adjacent piles can be merged at a time. The cost of merging is the sum of the masses of the two piles of stones. After merging, the stones adjacent to the two piles of stones will be adjacent to the new pile. Due to the different order of selection when merging, The total cost of the merger is also different.

The problem is: find a reasonable way to minimize the total cost and output the least cost.

State representation

f [ i ] [ j ] f[i][j] f [ i ] [ j ] All will beiipile of stones from i tojjj The method of combining piles of stones into a pile of stones

State calculation

f [ l ] [ r ] = M i n ( f [ l ] [ r ] , f [ l ] [ k ] + f [ k + 1 ] [ r ] + s [ r ] − s [ l − 1 ] ) f[l][r] = Min(f[l][r],f[l][k] + f[k + 1][r]+s[r] - s[l - 1]) f[l][r]=M i n ( f [ l ] [ r ] ,f[l][k]+f[k+1][r]s[r]s[l1 ] ) merge withkkk is the minimum cost of the left and right intervals of the boundary plus the cost of merging the current interval

const int N = 305;
int s[N];
int f[N][N];

int main() {
    
    
	int n;cin >> n;
	for (int i = 1;i <= n;++i)cin >> s[i];
	for (int i = 1; i <= n;++i)s[i] += s[i - 1];

	for(int len = 2; len <= n ;++len){
    
    //区间长度
		for (int i = 1;i + len - 1 <= n;++i) {
    
    //起点
			int l = i, r = i + len - 1;//区间端点
			f[l][r] = INF;
			for (int k = l;k < r;++k) {
    
    //枚举分界线
				f[l][r] = min(f[l][r], f[l][k]+ f[k + 1][r] + s[r] - s[l - 1]);
			}
		}
	}
	cout << f[1][n];
	return 0;
}

Guess you like

Origin blog.csdn.net/zzq0523/article/details/113100651