histcat

histcat

P1880 [NOI1995] Stone Merging

Problem#

There are $N$ piles of stones arranged around a circular playground, and we need to merge the stones into one pile in an orderly manner. It is stipulated that only two adjacent piles can be merged into a new pile at a time, and the number of stones in the new pile is recorded as the score for that merge.

Design an algorithm to calculate the minimum and maximum scores for merging $N$ piles of stones into one pile.

$1\leq N\leq 100$, $0\leq a_i\leq 20$.

Solution#

There is not much to say; the circular problem can be transformed into a linear problem of double the length.

Code#

#include<bits/stdc++.h>

using namespace std;

const int N = 110;
int a[2 * N];

int read()
{
	int f = 1, x = 0;
	char ch = getchar();
	while(ch < '0' || ch > '9')
	{
		if(ch == '-') f = -1;
		ch = getchar();
	}

	while(ch >= '0' && ch <= '9')
	{
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return f * x;
}
int n;

int f_min[2 * N][2 * N], f_max[2 * N][2 * N], sum[2 * N];

int main()
{
	n = read();
	memset(f_min, 0x3f, sizeof f_min);
	memset(f_max, -0x3f, sizeof f_max);
	for(int i = 1;i <= n;i++)
	{
		a[n + i] = a[i] = read();
	}

	for(int i = 1;i <= 2 * n;i++)
	{
		sum[i] = sum[i - 1] + a[i];
		f_min[i][i] = f_max[i][i] = 0;
	}

	for(int L = 1;L <= 2 * n;L++)
	{
		for(int i = 1;i + L - 1 <= 2 * n;i++)
		{
			int j = i + L - 1;
			for(int k = i;k <= j;k++)
			{
				f_min[i][j] = min(f_min[i][j], f_min[i][k] + f_min[k + 1][j] + sum[j] - sum[i - 1]);
				f_max[i][j] = max(f_max[i][j], f_max[i][k] + f_max[k + 1][j] + sum[j] - sum[i - 1]);
			}
		}
	}


	int min_ans = 0x3f3f3f3f, max_ans = -0x3f3f3f3f;

	for(int i = 1;i + n - 1 <= 2 * n;i++)
	{
		min_ans = min(min_ans, f_min[i][i + n - 1]);
		max_ans = max(max_ans, f_max[i][i + n - 1]); 
	}

	cout << min_ans << endl << max_ans;
	return 0;
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.