BZOJ1345: [Baltic2007]序列问题Sequence

1345: [Baltic2007]序列问题Sequence

Time Limit: 5 Sec  Memory Limit: 162 MB
Submit: 556  Solved: 274
[Submit][Status]

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

HINT

30%的测试数据 n<=500;
50%的测试数据 n <= 20,000。

Source

题解:

想了一中午无果,果断膜拜了hzwer的题解。。。

单调栈的解法还需要好好品味,看来我需要做一些单调栈的练习。

代码:

 1 var ans:int64;
 2     i,n,x,top:longint;
 3     sta:array[0..1500000] of longint;
 4 procedure main;
 5  begin
 6    readln(n);
 7    sta[0]:=maxlongint;top:=0;ans:=0;
 8    for i:=1 to n do
 9     begin
10       readln(x);
11       while (top>0) and (x>=sta[top]) do
12        begin
13          if x>=sta[top-1] then inc(ans,sta[top-1])
14          else inc(ans,x);
15          dec(top);
16        end;
17       inc(top);sta[top]:=x;
18     end;
19    for i:=1 to top-1 do inc(ans,sta[i]);
20    writeln(ans);
21  end;
22 
23 begin
24   assign(input,'input.txt');assign(output,'output.txt');
25   reset(input);rewrite(output);
26   main;
27   close(input);close(output);
28 end. 
View Code
原文地址:https://www.cnblogs.com/zyfzyf/p/3904835.html