1. 程式人生 > >Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0 - Round 2) E. Buy Low Sell High [貪心 II][數據結構 I]

Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0 - Round 2) E. Buy Low Sell High [貪心 II][數據結構 I]

fin 想想 ima 直接 圖片 test 只需要 數據結構 lan

題目:http://codeforces.com/contest/867/problem/E

技術分享圖片

題意:模擬股票操作,每天只能買一只股票或者賣一只股票或者什麽也不做,求最大利潤。

題解:仔細想想是非常簡單的一個貪心問題,理解為連續的多次貪心買入賣出可以合並為一次的買入賣出,且值為最優。只需要用一個最小堆每次尋找前面的最小且沒有被標記為購買點的值即可。如果自己為最小值,continue。如果那個值沒有被選過,為買入點,pop。如果那個值被選為了售出的點,那麽取消售出的標記,把當前點標記為售出點,利潤直接加為和堆頂的差值。

#include<bits/stdc++.h>
#define pii pair<int, int>
#define
mod 1000000007 #define mp make_pair #define pi acos(-1) #define eps 0.00000001 #define mst(a,i) memset(a,i,sizeof(a)) #define all(n) n.begin(),n.end() #define lson(x) ((x<<1)) #define rson(x) ((x<<1)|1) #define inf 0x3f3f3f3f typedef long long ll; typedef unsigned long long ull; using namespace std; const
int maxn = 3e5+5; priority_queue<pii,vector<pii>,greater<pii>>a; int has[maxn]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int i, j, k, m, n; cin>>n; ll ans =0; for(int i= 1;i<=n;++i) { cin>>k; a.push(mp(k,i));
if(a.top().first>=k)continue; ans+=k-a.top().first; if(!has[a.top().second]) { a.pop(); has[i]=1; } else{ has[a.top().second]=0; has[i]=1; } } cout<<ans<<endl; return 0; }

Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0 - Round 2) E. Buy Low Sell High [貪心 II][數據結構 I]