合并石子--Garsia-Wachs贪心

题意:

有n堆石子,每次可以合并相邻两个石子,代价为两堆石子的和,求将这堆石子合并为一堆的最小代价。

这道题可以用平衡树做,只是维护的东西很多很多,会非常难受

所以我就退而求其次,选择了ZJC大爷的卡常做法

1e5的数据范围也能在1s内轻松卡过啦!!!

思路与Garsia-Wachs算法一致

代码如下

#include<bits/stdc++.h>
using namespace std;
unsigned int tot;
unsigned long long a[500005];
int n;
int read()
{
	char c;
	int x;
	for(c=getchar();c!='-'&&(c>'9'||c<'0');c=getchar());
	if(c=='-')
	{
		x=0;
		for(c=getchar();c>='0'&&c<='9';c=getchar())
		x=x*10+c-'0';
		return -x;
	}
	else 
	{
		x=c-'0';
		for(c=getchar();c>='0'&&c<='9';c=getchar())
		x=x*10+c-'0';
		return x;
	}
}
unsigned long long ans;
	
void unionn(const unsigned int x)
{
	unsigned int i,j,d;
	unsigned long long tmp=a[x]+a[x-1];
	ans+=tmp;
	for(i=x;i<tot;++i) a[i]=a[i+1];
	tot--;
	for(j=x-1;a[j-1]<tmp&&j>1;--j)
	a[j]=a[j-1];
	a[j]=tmp;
	for(d=tot-j;j>2&&a[j-2]<=a[j];d=tot-j)
	{
		unionn(j-1); 
		j=tot-d;
	}
}
int main()
{
	freopen("mmm.in","r",stdin); 
	freopen("mmm.out","w",stdout);
	cin>>n;
	for(register unsigned int i=1;i<=n;i++)
	a[i]=read();
	for(register unsigned int i=1;i<=n;++i)
	{
		a[++tot]=a[i];
		while(tot>2&&a[tot-2]<=a[tot])
		unionn(tot-1);
	}
	while(tot>1) 
	unionn(tot);
	cout<<ans<<endl;
	return 0;
}
/*
5
186 64 35 32 103
*/

 

转载于:https://www.cnblogs.com/ENESAMA/p/10110001.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值