1068. 环形石子合并

题目链接

1068. 环形石子合并

\(n\) 堆石子绕圆形操场排放,现要将石子有序地合并成一堆。

规定每次只能选相邻的两堆合并成新的一堆,并将新的一堆的石子数记做该次合并的得分。

请编写一个程序,读入堆数 \(n\) 及每堆的石子数,并进行如下计算:

  • 选择一种合并石子的方案,使得做 \(n−1\) 次合并得分总和最大。
  • 选择一种合并石子的方案,使得做 \(n−1\) 次合并得分总和最小。

输入格式

第一行包含整数 \(n\),表示共有 \(n\) 堆石子。

第二行包含 \(n\) 个整数,分别表示每堆石子的数量。

输出格式

输出共两行:

第一行为合并得分总和最小值,

第二行为合并得分总和最大值。

数据范围

\(1≤n≤200\)

输入样例:

4
4 5 9 4

输出样例:

43
54

解题思路

区间dp

首先可以确定的一点:一定存在某个分界点使两边的点不会跨越这个分界点,不妨破环成链,将数组再复制一份,对 \(2*n\) 的区间进行求解长度为 \(n\) 时的最大值和最小值

  • 时间复杂度:\(O(n^3)\)

代码

// Problem: 环形石子合并
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1070/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=405,inf=0x3f3f3f3f;
int f[N][N][2],s[N],n,a[N];
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    	cin>>a[i];
    	a[i+n]=a[i];
    }
    for(int i=1;i<=2*n;i++)s[i]=a[i]+s[i-1];
    for(int i=1;i<=2*n;i++)f[i][i][0]=f[i][i][1]=0;
    for(int len=2;len<=n;len++)
    {
    	for(int l=1;l+len-1<=2*n;l++)
    	{
    		int r=l+len-1;
    		f[l][r][1]=inf;
    		f[l][r][0]=-inf;
    		for(int t=l;t+1<=r;t++)
    		{
    			f[l][r][0]=max(f[l][r][0],f[l][t][0]+f[t+1][r][0]+s[r]-s[l-1]);
    			f[l][r][1]=min(f[l][r][1],f[l][t][1]+f[t+1][r][1]+s[r]-s[l-1]);
    		}
    	}
    }
    int res[2]={-inf,inf};
    for(int l=1;l<=n;l++)
    {
    	int r=l+n-1;
    	res[0]=max(res[0],f[l][r][0]);
    	res[1]=min(res[1],f[l][r][1]);
    }
    cout<<res[1]<<'\n'<<res[0];
    return 0;
}
posted @ 2022-03-14 20:21  zyy2001  阅读(172)  评论(0编辑  收藏  举报