CodeForces

来源:互联网 发布:ubuntu修改hosts翻墙 编辑:程序博客网 时间:2024/06/06 10:47

根据题意可以想到 找所有正序的对,先找最小和最大的,本想着 线段树维护来着,,,

这里的做法是优先队列保存最小值,遇到大于优先队列堆顶的元素 ans 加上差值,然后这个元素入队两次

贪心的做法之所以有他的正确性,就是入队两次的元素,一次相当于本身,另一次相当于传递前一个值找到最大的差值(也就是答案)


#include<bits/stdc++.h>using namespace std;typedef long long ll;priority_queue<int, vector<int>, greater<int> > qu;int n; ll x, ans = 0;int main() {    scanf("%d", &n);    for(int i = 0; i < n; ++i) {        scanf("%I64d", &x);        if(qu.empty() || qu.top() >= x) {            qu.push(x);        }        else {            ans += (x - qu.top()); qu.pop();            qu.push(x);qu.push(x);        }    }    printf("%I64d\n", ans);    return 0;}