43 lines
1.0 KiB
C++
43 lines
1.0 KiB
C++
#include <cstdio>
|
||
#include <cstring>
|
||
#include <algorithm>
|
||
#include <iostream>
|
||
#include <set>
|
||
using namespace std;
|
||
const int INF = 0x3f3f3f3f;
|
||
|
||
const int N = 40000 + 10;
|
||
int n, ans;
|
||
|
||
// AC 263 ms
|
||
set<int> s;
|
||
/*
|
||
注意事项
|
||
1.set中lower_bound返回的是迭代器it
|
||
2.为了防止lower_bound返回指针是set.end()–>即寻找不到,可以在set中预先加入两个哨兵
|
||
*/
|
||
int main() {
|
||
//加快读入
|
||
ios::sync_with_stdio(false), cin.tie(0);
|
||
cin >> n;
|
||
|
||
//加入哨兵是个好习惯,防止查找最小数前驱,或,最大数后继时,发生边界问题
|
||
s.insert(-INF), s.insert(INF);
|
||
|
||
for (int i = 1; i <= n; i++) {
|
||
int x;
|
||
cin >> x;
|
||
auto it = s.lower_bound(x);
|
||
|
||
if (i == 1) //第一天的最小波动值为第一天的营业额 a1
|
||
ans += abs(x);
|
||
else
|
||
ans += min(abs(x - *(--it)), abs(x - *it));
|
||
|
||
// x入set
|
||
s.insert(x);
|
||
}
|
||
//输出结果
|
||
printf("%d\n", ans);
|
||
return 0;
|
||
} |