You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.2 KiB

2 years ago
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
/*
使vector-INFINF使lower_boundupper_bound
*/
// 727 ms
vector<int> a;
int main() {
int n;
cin >> n;
a.push_back(-INF), a.push_back(INF);
//首次插入
int x;
int res = 0;
//后续插入
for (int i = 1; i <= n; i++) {
cin >> x;
if (i == 1)
res += x;
else {
int prev = lower_bound(a.begin(), a.end(), x) - a.begin();
if (a[prev] != x) prev = lower_bound(a.begin(), a.end(), x) - a.begin() - 1;
//如果序列之中没有等于当前的数,那我们取严格小于当前的数
int next = upper_bound(a.begin(), a.end(), x) - a.begin(); //后继
//按题目要求来计算
res += min(abs(x - a[prev]), abs(a[next] - x));
}
//将x放入vector中
a.insert(lower_bound(a.begin(), a.end(), x), x);
}
//输出
printf("%d\n", res);
return 0;
}