##问题描述
某股票交易所请你编写一个程序,根据开盘前客户提交的订单来确定某特定股票的开盘价和开盘成交量。
该程序的输入由很多行构成,每一行为一条记录,记录可能有以下几种:
1. buy p s 表示一个购买股票的买单,每手出价为p,购买股数为s。
2. sell p s 表示一个出售股票的卖单,每手出价为p,出售股数为s。
3. cancel i表示撤销第i行的记录。
如果开盘价为p0,则系统可以将所有出价至少为p0的买单和所有出价至多为p0的卖单进行匹配。因此,此时的开盘成交量为出价至少为p0的买单的总股数和所有出价至多为p0的卖单的总股数之间的较小值。
你的程序需要确定一个开盘价,使得开盘成交量尽可能地大。如果有多个符合条件的开盘价,你的程序应当输出最高的那一个。
##解题思路
对价格排序,然后枚举每个价格并利用前缀和(sell)和后缀和(buy)得出当前价格的数量
实现上,为了将多个相同价格的记录合并,使用了map进行存储;
#include <cstdio>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int N = 5005;
struct GP
{
bool buy;
double price;
int tot;
void read(bool b)
{
buy = b;
scanf("%lf%d", &price, &tot);
}
}gp[N];
map<double, long long> buy, sell;
set<double> price;
int main()
{
char op[10];
freopen("4.txt", "r", stdin);
for (int line = 1; ~scanf("%s", op); line++)
{
if (op[0] == 'c')
{
int x;
scanf("%d", &x);
(gp[x].buy ? buy : sell)[gp[x].price] -= gp[x].tot;
}
else
{
gp[line].read(op[0] == 'b');
price.insert(gp[line].price);
(gp[line].buy ? buy : sell)[gp[line].price] += gp[line].tot;
}
}
long long bsum = 0;
for (map<double, long long>::iterator i = buy.begin(); i != buy.end(); i++)bsum += i->second;
long long ssum = 0;
double ansprice = 0;
long long anstot = 0;
for (set<double>::iterator i = price.begin(); i != price.end(); i++)
{
if (!(sell[*i] || buy[*i]))continue;
ssum += sell[*i];
long long x = min(ssum, bsum);//在当前价格下,成交量应该等于合法买入成交量或者可以合法卖出成交量中的最小值。
if (x >= anstot)
{
anstot = x;
ansprice = *i;
}
bsum -= buy[*i];
}
printf("%.2f %lld\n", ansprice, anstot);
return 0;
}
from: http://erona.me/2015/03/21/CCF%E9%9B%86%E5%90%88%E7%AB%9E%E4%BB%B7/