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);
}

猜你喜欢

转载自blog.csdn.net/xumingyang0/article/details/85147460