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;
}