2018中国大学生程序设计竞赛 – 网络选拔赛 1001 Buy and Resell [模拟]

博客围绕1 - n个货物买卖问题展开,题目要求在某个点买入货物,在后面的点卖出,可同时买多个,需计算最大利润和最小交易次数。题解采用模拟运算,前i天可买入并加入待卖序列,若第i天最小待卖价格比当天价格小则可卖出,还给出了相应代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                              1001 Buy and Resell

 题目:有1-n个货物,可以在某个点buy,然后在后面的点resell,可以同时买多个,问最大的利润和最小的交易次数。

题解:模拟运算,前 i 天都是可以买的,加入待卖序列(x, 0),对于第 i 天如果最小的待卖的价格比a[i]小,那么说明可以卖,然后将(a[i], 1)加入队列,表示已经卖出,这样模拟一下;

代码:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5+7;

int n;
ll a[maxn];
struct node{
    ll num,index;
    node(ll a,ll b)
    {
        num = a;
        index = b;
    }
    friend bool operator < (node a,node b)
    {
           if(a.num == b.num) return a.index < b.index;
           return a.num > b.num;
    }
};

priority_queue <node> q;

int main()
{
    //freopen("in.txt", "r", stdin);
	int t; scanf("%d", &t);
	while(t--)
	{
		scanf("%d", &n);
		ll x = 0, y = 0;
		for(int i = 1; i <= n; i++) {
            scanf("%lld", &a[i]);
            q.push(node(a[i], 0));
            node temp = q.top();
            if(a[i]>temp.num) {
                x += (a[i] - temp.num);
                q.pop();
                q.push(node(a[i], 1));
            }
		}
        while(!q.empty()) {
            if(q.top().index == 1) y++;
            q.pop();
        }
	    printf("%lld %lld\n", x, 2ll*y);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值