【CCF】101412_3集合竞价

试题编号: 201412-3
试题名称: 集合竞价
时间限制: 1.0s
内存限制: 256.0MB
问题描述:
问题描述
  某股票交易所请你编写一个程序,根据开盘前客户提交的订单来确定某特定股票的开盘价和开盘成交量。
  该程序的输入由很多行构成,每一行为一条记录,记录可能有以下几种:
  1. buy p s 表示一个购买股票的买单,每手出价为p,购买股数为s。
  2. sell p s 表示一个出售股票的卖单,每手出价为p,出售股数为s。
  3. cancel i表示撤销第i行的记录。
  如果开盘价为p 0,则系统可以将所有出价至少为p 0的买单和所有出价至多为p 0的卖单进行匹配。因此,此时的开盘成交量为出价至少为p 0的买单的总股数和所有出价至多为p 0的卖单的总股数之间的较小值。
  你的程序需要确定一个开盘价,使得开盘成交量尽可能地大。如果有多个符合条件的开盘价,你的程序应当输出最高的那一个。
输入格式
  输入数据有任意多行,每一行是一条记录。保证输入合法。股数为不超过10 8的正整数,出价为精确到恰好小数点后两位的正实数,且不超过10000.00。
输出格式
  你需要输出一行,包含两个数,以一个空格分隔。第一个数是开盘价,第二个是此开盘价下的成交量。开盘价需要精确到小数点后恰好两位。
样例输入
buy 9.25 100
buy 8.88 175
sell 9.00 1000
buy 9.00 400
sell 8.92 400
cancel 1
buy 100.00 50
样例输出
9.00 450
评测用例规模与约定
  对于100%的数据,输入的行数不超过5000。

思路:

把买和卖的记录全都存放在容器里,然后按照出价自小到大排序,根据出价遍历求得最大成交量。

注意p0必然是某个出价,不可能是其他值。

此外读题要注意匹配的是买单出价至少为p0和卖单出价最多为p0,即买单>=p0,卖单<=p0。

代码实现:

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

struct D{
	string type;
	double price;
	int num;
};

bool cmp(D a, D b){
	return a.price < b.price;
} 

int main(){
	char str[1000];
	vector<D> arr;
	int count = 0;  //用于记录共输入几条记录 
	while(scanf("%s", str) != EOF){
		string a(str);  //把char数组转换成string 
		count ++; 
		if(a == "buy" || a == "sell"){
			D tmp;
			tmp.type = a;
			scanf("%lf%d", &tmp.price, &tmp.num);
			arr.push_back(tmp);
		}
		else if(a == "cancel"){
			int i;
			scanf("%d", &i);
			arr.erase(arr.begin()+i-1);  //删除第i条记录 
		}	
	}
	sort(arr.begin(), arr.end(), cmp);
	int max = 0;
	double ans_p;
	for(vector<D>::iterator it = arr.begin(); it != arr.end(); it++){
		double tmp_price = (*it).price;
		int sum_buy = 0, sum_sell = 0, tmp_sum = 0;
		for(vector<D>::iterator j = arr.begin(); j != arr.end(); j++){
			if((*j).type == "buy" && (*j).price >= tmp_price){
				sum_buy += (*j).num;
			}
			else if((*j).type == "sell" && (*j).price <=tmp_price){
				sum_sell += (*j).num;
			}
		}
		if(sum_buy>sum_sell)  tmp_sum = sum_sell;
		else tmp_sum = sum_buy;
		if(tmp_sum > max){
			max = tmp_sum;
			ans_p = tmp_price;
		}
	}
	printf("%.2lf %d", ans_p, max);
	return 0;
}

c语言中输入结束是EOF(即-1),所以采用了字符数组,然后再转换为string进行判断。


猜你喜欢

转载自blog.csdn.net/u014322206/article/details/78669914
今日推荐