2018中國大學生程序設計競賽 - 網絡選拔賽--HDU 6438 Buy and Resell(貪心)

題意:

有 n 個城市,每個城市可以買一個價值爲 ai 的東西或者賣一個價值爲 ai 的東西,假設你一開始有無數的錢,問你經過這些城市最多可以賺多少利潤。

題解:

有利潤就要當前的值大於你買進去的值,比如第一個樣例:(10-2,9-1) 和 (10-1,9-2)是一樣的。

如果我們只是這樣去求答案是不對的,因爲在第一個樣例中 2 是大於 1的,這樣就很虧,但是我們可以發現先 2-1 再10-2 和10-1 是一樣的,所以我們維護一個優先隊列去保存從小到大(用過優先),答案就是差值。

#include <algorithm>
#include  <iostream>
#include   <cstdlib>
#include   <cstring>
#include    <cstdio>
#include    <string>
#include    <vector>
#include    <bitset>
#include     <stack>
#include     <cmath>
#include     <deque>
#include     <queue>
#include      <list>
#include       <set>
#include       <map>
#define mem(a, b) memset(a, b, sizeof(a))
#define inf 0x7ffffff
#define pi acos(-1)
using namespace std;
typedef long long ll;

struct node{
    ll num, mark;
    node(){};
    node(ll _num, ll _mark){
        num = _num;
        mark = _mark;
    }
    friend bool operator < (node a, node b){
        if(a.num == b.num){
            return a.mark < b.mark;
        }
        return a.num > b.num;
    }
}; 

priority_queue<node> q;

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        ll n, ans = 0, cnt = 0;
        scanf("%lld", &n);
        for(int i = 0; i < n; i++){
            ll a;
            scanf("%lld", &a);
            node temp, now = node(a, 0);
            q.push(now);
            temp = q.top();
            if(a > temp.num){
                ans += a - temp.num;
                q.pop();
                q.push(node(a, 1));
            }
        }
        while(!q.empty()){
            node temp = q.top();
            q.pop();
            if(temp.mark){
                cnt++;
            }
        }
        printf("%lld %lld\n", ans, cnt*2);
    }
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章