BZOJ 1345: [Baltic2007]序列问题Sequence 单调栈。、

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kidsummer/article/details/83961705

Description

对于一个给定的序列a1,…,an,我们对它进行一个操作reduce(i),该操作将数列中的元素ai和ai+1用一个元素max

(ai,ai+1)替代,这样得到一个比原来序列短的新序列。这一操作的代价是max(ai,ai+1)。进行n-1次该操作后,

可以得到一个长度为1的序列。我们的任务是计算代价最小的reduce操作步骤,将给定的序列变成长度为1的序列。

Input

第一行为一个整数n( 1 <= n <= 1,000,000 ),表示给定序列的长度。

接下来的n行,每行一个整数ai(0 <=ai<= 1, 000, 000, 000),为序列中的元素。

Output

只有一行,为一个整数,即将序列变成一个元素的最小代价。

Sample Input

3
1
2
3

Sample Output

5

思路。

维护一个单调递减的栈。

emmmmmm

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
int a[N],h[N],n;
long long ans;
int main(){
	scanf("%d",&n);
	for (int i = 0; i < n; i++)
		scanf("%d",&a[i]);
	int t = 0;

	for (int i = 0; i < n; i++){
		while(t != 0 && h[t] <= a[i]){
			if (t != 1 && h[t-1] < a[i])
				ans += h[t-1]; 
			else ans += a[i];
			t--;
		}
		h[++t] = a[i];
	}

	while(t > 1) ans += h[--t];
	printf("%lld\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/kidsummer/article/details/83961705
今日推荐