1. 程式人生 > >51nod 2206 低買高賣&codeforces867E Buy Low Sell High

51nod 2206 低買高賣&codeforces867E Buy Low Sell High

題目

Solution

用堆儲存最小值,遇到大於堆頂的元素就把ans加上差值,然後這個元素入隊兩次,入隊兩次是為了有一次“後悔”的機會,也就是先選著,遇到更好的就替換掉

Code

#include<bits/stdc++.h>
using namespace std;
int i,ans,x,n;
priority_queue<int,vector<int>,greater<int> >q;
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return
p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++; } inline int rd(){ int x=0,fl=1;char ch=gc(); for (;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1; for (;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48); return x*fl; } inline void wri(int a){
if(a<0)a=-a,putchar('-');if(a>=10)wri(a/10);putchar(a%10|48);} inline void wln(int a){wri(a);puts("");} int main(){ n=rd(); for (i=0;i<n;i++){ x=rd(); if (q.empty() || x<=q.top()) q.push(x); else ans+=x-q.top(),q.pop(),q.push(x),q.push(x); } printf("%d",ans); }