问题描述
试题编号: | 201412-3 |
试题名称: | 集合竞价 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 某股票交易所请你编写一个程序,根据开盘前客户提交的订单来确定某特定股票的开盘价和开盘成交量。 输入格式 输入数据有任意多行,每一行是一条记录。保证输入合法。股数为不超过108的正整数,出价为精确到恰好小数点后两位的正实数,且不超过10000.00。 输出格式 你需要输出一行,包含两个数,以一个空格分隔。第一个数是开盘价,第二个是此开盘价下的成交量。开盘价需要精确到小数点后恰好两位。 样例输入 buy 9.25 100 样例输出 9.00 450 评测用例规模与约定 对于100%的数据,输入的行数不超过5000。 |
这道题目的解题思路相对来说比较简单。对买入的股票做升序处理,对卖出的股票做降序处理,然后对所有记录的单价进行遍历,统计出所有买入股票的总票数和卖出股票的总票数。
这道题第一次做只拿了30分,原因在于没有把撤销操作算进来,这实在是太可惜了。
但是感觉通过这段时间的练习,自己在改善程序性能方面有了很大的提高。这里我通过空间换取时间,将前i个数的求和记录在数组当中,这样就防止了在对所有记录单价进行遍历的时候,重复求和所消耗的时间。
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define MAX 5005
#define INF 0x3fffffff
struct Info
{
double price;
long long num;
int type;//1表示buy,2表示sell
int cancel;
};
bool cmp1(struct Info a,struct Info b)
{
return a.price>b.price;
}
bool cmp2(struct Info a,struct Info b)
{
return a.price<b.price;
}
struct Info buy[MAX];
struct Info sell[MAX];
struct Info record[MAX];
long long pbuy[MAX];
long long psell[MAX];
int main()
{
int cnt=0;
char str[10];
double a;
int b;
while(scanf("%s",str)!=EOF)
{
if(strcmp(str,"buy")==0)
{
scanf("%lf %lld",&record[cnt].price,&record[cnt].num);
record[cnt].type=1;
record[cnt].cancel=0;
cnt++;
}
else if(strcmp(str,"sell")==0)
{
scanf("%lf %lld",&record[cnt].price,&record[cnt].num);
record[cnt].type=0;
record[cnt].cancel=0;
cnt++;
}
else if(strcmp(str,"cancel")==0)
{
int id;
scanf("%d",&id);
record[id-1].cancel=1;
record[cnt].cancel=1;
cnt++;//此处要注意了,cnt必须自增一个单位
}
}
int cnta=1;
int cntb=1;
for(int i=0;i<cnt;i++)
{
if(record[i].type==1&&record[i].cancel==0)
{
buy[cnta++]=record[i];
}
if(record[i].type==0&&record[i].cancel==0)
{
sell[cntb++]=record[i];
}
}
sort(buy+1,buy+cnta,cmp1);
sort(sell+1,sell+cntb,cmp2);
sort(record,record+cnt,cmp1);
pbuy[0]=0;
psell[0]=0;
pbuy[1]=buy[1].num;
psell[1]=sell[1].num;
for(int i=2;i<cnta||i<cntb;i++)
{
if(i<cnta) pbuy[i]=pbuy[i-1]+buy[i].num;
if(i<cntb) psell[i]=psell[i-1]+sell[i].num;
}
double ansp=0;
long long ansn=0;
int k=1;
int j;
for(int i=0;i<cnt;i++)
{
if(record[i].cancel==1) continue;
for(;k<cnta;k++)
{
if(buy[k].price<record[i].price) break;
}
for(j=1;j<cntb;j++)
{
if(sell[j].price>record[i].price) break;
}
long long res=min(psell[j-1],pbuy[k-1]);
if(res>ansn)
{
ansn=res;
ansp=record[i].price;
}
else if(res==ansn)
{
ansp=max(record[i].price,ansp);
}
// if(psell[j-1]<pbuy[k-1])
// {
// if(psell[j-1]>ansn)
// {
// ansn=psell[j-1];
// ansp=record[i].price;
// }
// else if(psell[j-1]==ansn)
// {
// ansp=max(record[i].price,ansp);
// }
// }
// if(psell[j-1]>=pbuy[k-1])
// {
// if(pbuy[k-1]>ansn)
// {
// ansn=pbuy[k-1];
// ansp=record[i].price;
// }
// else if(pbuy[k-1]==ansn)
// {
// ansp=max(record[i].price,ansp);
// }
// }
}
printf("%.2f %lld\n",ansp,ansn);
return 0;
}