HDUOJ 6438 Buy and Resell

HDUOJ 6438 Buy and Resell

题目链接

Problem Description

The Power Cube is used as a stash of Exotic Power. There are n cities numbered 1,2,…,n where allowed to trade it. The trading price of the Power Cube in the i-th city is ai dollars per cube. Noswal is a foxy businessman and wants to quietly make a fortune by buying and reselling Power Cubes. To avoid being discovered by the police, Noswal will go to the i-th city and choose exactly one of the following three options on the i-th day:

  1. spend ai dollars to buy a Power Cube
  2. resell a Power Cube and get ai dollars if he has at least one Power Cube
  3. do nothing

Obviously, Noswal can own more than one Power Cubes at the same time. After going to the n cities, he will go back home and stay away from the cops. He wants to know the maximum profit he can earn. In the meanwhile, to lower the risks, he wants to minimize the times of trading (include buy and sell) to get the maximum profit. Noswal is a foxy and successful businessman so you can assume that he has infinity money at the beginning.

Input

There are multiple test cases. The first line of input contains a positive integer T (T≤250), indicating the number of test cases. For each test case:
The first line has an integer n. (1≤n≤1e5)
The second line has n integers a1,a2,…,an where ai means the trading price (buy or sell) of the Power Cube in the i-th city. (1≤ai≤1e9)
It is guaranteed that the sum of all n is no more than 5e5.

Output

For each case, print one line with two integers —— the maximum profit and the minimum times of trading to get the maximum profit.

Sample Input

3
4
1 2 10 9
5
9 5 9 10 5
2
2 1

Sample Output

16 4
5 2
0 0

思维+优先队列~
简单来看,我们不难发现就是 2 ∗ k 2*k 2k 组,答案就是:
a k + 1 + a k + 2 + ⋯ + a 2 k − ( a 1 + a 2 + ⋯ + a k ) a_{k+1}+a_{k+2}+\cdots+a_{2k}-(a_1+a_2+\cdots +a_k) ak+1+ak+2++a2k(a1+a2++ak)
但这样其实很难想,我们把这个式子调整一下就会得到:
a 2 − a 1 + a 3 − a 2 + a 4 − a 2 + a 4 − a 3 + ⋯ = a 2 k − a 2 k − 1 a_2-a_1+a_3-a_2+a_4-a_2+a_4-a_3+\cdots =a_{2k}-a_{2k-1} a2a1+a3a2+a4a2+a4a3+=a2ka2k1
对上面的式子很容易用优先队列实现,即当出现元素大于队头时,再额外插入一次,当队列某元素为空时,次数加 2 2 2 即可,AC代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
map<ll,ll>mp;
priority_queue<ll,vector<ll>,greater<ll>>q;
int t,n;
int main(){
    
    
    scanf("%d",&t);
    while(t--){
    
    
        mp.clear();
        ll ans=0,x;
        int num=0;
        while(!q.empty()) q.pop();
        scanf("%d",&n);
        while(n--){
    
    
            scanf("%lld",&x);
            if(!q.empty()&&x>q.top()){
    
    
                if(mp[q.top()]) mp[q.top()]--;
                else num+=2;
                mp[x]++;
                ans+=x-q.top();
                q.pop();
                q.push(x);
            }
            q.push(x);
        }
        printf("%lld %d\n",ans,num);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/108671914
今日推荐