[Codeforces 867.E] Buy Low Sell High(堆)

E. Buy Low Sell High

time limit per test:2 seconds
memory limit per test:256 megabytes
input:standard input
output:standard output
You can perfectly predict the price of a certain stock for the next $N$ days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don’t own any. At the end of the $N$ days you would like to again own zero shares, but want to have as much money as possible.

Input

Input begins with an integer $N$ $(2≤N≤3·10^5)$, the number of days.

Following this is a line with exactly $N$ integers $p_1,p_2,…,p_N$ $(1≤p_i≤10^6)$. The price of one share of stock on the $i$-th day is given by $p_i$.

Output

Print the maximum amount of money you can end up with at the end of $N$ days.

Examples

input output
9
10 5 4 7 9 12 6 2 10
20
20
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4
41

Note

In the first example, buy a share at $5$, buy another at $4$, sell one at $9$ and another at $12$. Then buy at $2$ and sell at $10$. The total profit is $-5-4+9+12-2+10=20$.


解题思路

挺经典的一道题。
在 $a$ 处买入并在 $b$ 处卖出等效于在 $a$ 处买入、在 $c$ 处卖出并在 $c$ 处买入、再在 $b$ 处卖出。看起来很傻但是把题变简单了:只要能赚钱就卖,如果以后发现更好的差价就反悔,回到之前卖掉的地方买回来再卖出去。
程序实现很巧妙,维护一个小根堆,如果当前元素小于堆顶就插进堆中;否则,弹出堆顶元素,答案加上差价,并将当前元素入堆两次。这样,当它第一次被弹出时相当于反悔了一次,第二次被弹出就表示真的把它卖了出去。

时间复杂度:$O(n\log n)$


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# include<bits/stdc++.h>

using namespace std;

//此处省略 define 的一些东西和读入输出优化

const int N = 300005;

int n, p;
LL ans;
priority_queue< int, vector<int>, greater<int> > q;

int main(){
in(n);
fo1(i, 1, n){
in(p);
if(q.empty() || p <= q.top()) q.push(p);
else{
ans += 1ll * p - q.top();
q.pop();
q.push(p); q.push(p);
}
}
outln(ans);
return 0;
}