环形石子合并(区间dp)

87 篇文章 1 订阅
这篇博客探讨了环形石子合并问题的解决方案,与传统石子合并区别在于允许首位合并。通过使用双倍大小的数组和前缀和,博主介绍了如何利用动态规划(dp[l][r])计算区间最大值,并枚举中间点来求解石子合并的最小代价。
摘要由CSDN通过智能技术生成

在这里插入图片描述

思路:和普通石子合并不同的是可以首位合并那么我们吧数组开2倍后面n+1到2n存储1到n相同的东西,dp[l][r]表示从L-R区间的最大值,每次石子都是有之前的2堆合并的,所以枚举中间点即可,dp[l][r]=max(dp[l][r],dp[l][k]+dp[k+1][r]+val[l][r]),其中val是合并L-R区间所需的代价我们用前缀和即可算出。

#pragma GCC optimize(2)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<iomanip>
#include<cstring>
#include<time.h>

using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e6+10;
const int M=1e3+10;
const int inf=0x3f3f3f3f;
const int maxx=2e5+7;
const double eps=1e-6;
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
         write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    ll res=1%p;
    while(b)
    {
        if(b&1)
            res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}
int f1[405][405];
int f2[405][405];
int w[405];
int s[405];
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>w[i];
        w[i+n]=w[i];
    }
    memset(f1,-inf,sizeof f1);
    memset(f2,inf,sizeof f2);
    for(int i=1;i<=2*n;i++) s[i]=s[i-1]+w[i];

    for(int len=1;len<=n;len++)
    {
        for(int j=1;j+len-1<=n*2;j++)
        {
           int l=j,r=j+len-1;
           if(len==1) f1[l][r]=f2[l][r]=0;
           else{
                for(int k=l;k<r;k++)
               {
                 f1[l][r]=max(f1[l][r],f1[l][k]+f1[k+1][r]+s[r]-s[l-1]);
                 f2[l][r]=min(f2[l][r],f2[l][k]+f2[k+1][r]+s[r]-s[l-1]);      
               }
           }
          
        }
    }
    int res1=0,res2=inf;
    for(int i=1;i<=n;i++){
        res1=max(res1,f1[i][i+n-1]);
        res2=min(res2,f2[i][i+n-1]);
    }
    cout<<res2<<endl;
    cout<<res1<<endl;

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值