首页 技术 正文
技术 2022年11月19日
0 收藏 706 点赞 2,744 浏览 1598 个字

题目链接:

https://www.lydsy.com/JudgeOnline/problem.php?id=1345

题目大意:

对于一个给定的序列a1,…,an,我们对它进行一个操作reduce(i),该操作将数列中的元素ai和ai+1用一个元素max(ai,ai+1)替代,这样得到一个比原来序列短的新序列。这一操作的代价是max(ai,ai+1)。进行n-1次该操作后,可以得到一个长度为1的序列。我们的任务是计算代价最小的reduce操作步骤,将给定的序列变成长度为1的序列。

思路:

由贪心可知,每个数合并的对象为离这个数最近的并且大于等于这个数的值。可以用单调栈找出来离它最近的并且比它大的数字。我这里用了两次单调栈,第一次找出右边第一个大于等于a[i]的数,第二次找出左边大于等于a[i]的数。

 #include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);//不可再使用scanf printf
#define Max(a, b) ((a) > (b) ? (a) : (b))//禁用于函数,会超时
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Mem(a) memset(a, 0, sizeof(a))
#define Dis(x, y, x1, y1) ((x - x1) * (x - x1) + (y - y1) * (y - y1))
#define MID(l, r) ((l) + ((r) - (l)) / 2)
#define lson ((o)<<1)
#define rson ((o)<<1|1)
#define Accepted 0
#pragma comment(linker, "/STACK:102400000,102400000")//栈外挂
using namespace std;
inline int read()
{
int x=,f=;char ch=getchar();
while (ch<''||ch>''){if (ch=='-') f=-;ch=getchar();}
while (ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
typedef long long ll;
const int maxn = + ;
const int MOD = ;//const引用更快,宏定义也更快
const int INF = 1e9 + ;
const double eps = 1e-;
ll a[maxn];
stack<ll>q;
ll ans[maxn];
bool vis[maxn]; int main()
{
ll n;
ll mmax = ;
ll tot = ;
scanf("%lld", &n);
for(int i = ; i <= n; i++)
{
scanf("%lld", &a[i]);
mmax = max(mmax, a[i]);
while(!q.empty() && a[q.top()] <= a[i])//顺序扫一遍 维护递减的单调栈 求解i右边第一个大于a[i]的值
{
vis[q.top()] = ;
ans[q.top()] = a[i];
q.pop();
}
q.push(i);
}
while(!q.empty())q.pop();
for(int i = n; i >= ; i--)
{
while(!q.empty() && a[q.top()] <= a[i])//逆序扫一遍 维护递减的单调栈 求解i左边第一个大于a[i]的值
{
if(vis[q.top()])ans[q.top()] = min(ans[q.top()], a[i]);
else ans[q.top()] = a[i], vis[q.top()] = ;
q.pop();
}
q.push(i);
}
int cnt = ;
for(int i = ; i <= n; i++)if(vis[i])cnt++, tot += ans[i];
if(cnt == n)tot -= mmax;
cout<<tot<<endl;
return Accepted;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774