Luo Valley / Codeforces CF865D solution to a problem

If you want to go back depth study greedy portal .


Description:

Known Next \ (n \) days of the stock price, you can buy a day the day of the stock, to sell existing stock, or do nothing, seeking \ (n \) maximum profit after day.

Method

We can quickly think of a greedy strategy: the minimum purchase price of the stock, you can sell to make money the same day.

Clearly we can see, the above greedy strategy is wrong, because we buy the stock can wait until you can make the most of the day to sell.

We consider design a strategy to go back, so that all cases can get greedy global optimal solution. (Ie go back go back design strategy automata)

Define \ (C_ {buy} \) to buy a global optimal solution price of the day, \ (C_ {Sell} \) is a global optimal solution selling price of the day, then:
\ [C_ {Sell} - C_ {buy} = \ left ( C_ {sell} -C_i \ right) + \ left (C_i-C_ {buy} \ right) \]

\ (C_i \) any day stock price.

That is the price we have to buy a minimum share price of the largest stock to sell in order to get the maximum profit. We put current prices into a small heap root once (this is more than the text of greedy greedy strategy), to determine whether the current price is greater than the top of the heap, if it is larger than, the difference will be recognized in our global optimal solution , then the current price into a small heap root (this is go back operations). The equivalent to our current stock price if it is not the optimal solution, to no avail, and finally global optimal solution can be obtained.

The above equation to be known strategy automata go back go back, because we do not repeat update global optimal solution, global optimal method of intermediate terms but quickly get eliminated by the difference.

(If not yet understood that this question, can look at the code, a detailed Notes)

Code:

#include<bits/stdc++.h>
#define int long long 
using namespace std;
inline void read(int &x)
{
    int f=1;x=0;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}
priority_queue<int,vector<int>,greater<int> >qu;//开一个小根堆 
int n;
int ans=0;//全局最优解 
signed main()
{
    read(n);
    ans=0;
    for(int i=1,x;i<=n;i++)
    {
        read(x);//当前的股票价格 
        qu.push(x);//贪心策略:买价格最小的股票去买价格最大的股票 
        if(!qu.empty()&&qu.top()<x)//假如当前的股票价格不是最优解 
        {
            ans+=x-qu.top();//将差值计入全局最优解 
            qu.pop();//将已经统计的最小的股票价格丢出去 
            qu.push(x);//反悔策略:将当前的股票价格再放入堆中,即记录中间变量(等式中间无用的Ci) 
        }
    }
    printf("%lld\n",ans);//输出全局最优解 
    return 0;
} 

Guess you like

Origin www.cnblogs.com/nth-element/p/11792218.html