CCF-CSP 201412-3集合竞价 暴力算法 简单思路 满分题解

CCF-CSP 201412-3集合竞价 暴力算法 简单思路 满分题解

题目链接:201412-3集合竞价

CSP官网数据有误,请移步:AcWing 集合竞价

思路:

  • 股数最大为108,因此采用long long类型存储股数
  • 设置一个结构体,便于存储股数、价格、操作类型
  • 对于类型,0表示不存在,1表示买,2表示卖
  • 最后输出的价格一定为某个操作的价格,则可以遍历整个结构体,统计买的总股数和卖的总股数,最后进行更新
  • 控制小数位数输出的方法:cout<<fixed<<setprecision(2)<<p_out<<" ";,带上头文件#include<iomanip>

代码如下:

#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
typedef long long LL;
const int N = 5e3+10;
struct op{
    int type;//0表示不存在,1表示买,2表示卖
    double p;//价格
    int s;//股数
}op[N];
int n;//输入的记录总数
int main()
{
    string opt;
    int t;
    //数据预处理
    while(cin>>opt)
    {
        if(opt=="buy")
        {
            //注意++n只有一次
            cin>>op[++n].p>>op[n].s;
            op[n].type=1;
        }
        else if(opt=="sell")
        {
            cin>>op[++n].p>>op[n].s;
            op[n].type=2;
        }
        else
        {
            cin>>t;
            op[t].type=0;
            n++;
        }
    }
    double p_out = 0.0;//用于输出p
    LL s_out = 0;//用于输出s
    for(int i=1;i<=n;i++)
    {
        if(!op[i].type)continue;//当前记录已被删除
        double t = op[i].p;
        LL sum_buy = 0;
        LL sum_sell = 0;
        //遍历所有点
        for(auto x:op)
        {
            //buy
            if(x.type==1&&x.p>=t)
            {
                sum_buy += x.s;
            }
            //sell
            else if(x.type==2&&x.p<=t)
            {
                sum_sell += x.s;
            }
        }
        //更新
        if(s_out<min(sum_buy,sum_sell)||(s_out==min(sum_buy,sum_sell)&&t>=p_out))
        {
            p_out = t;
            s_out = min(sum_buy,sum_sell);
        }
    }
    cout<<fixed<<setprecision(2)<<p_out<<" ";
    cout<<s_out<<endl;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值