题目链接:
题目大意:
1.是统计每个时间校园内有多少辆车
2.是找出在校园内呆的时间最久的车
比较肉的模拟类问题,知道怎么去除无效的数据,直接模拟就可以了。
有效的配对是指紧挨着的两个in和out,也就是说连续的多个in取最后一个为有效,连续多个out取第一个为有效,最后如果有in没有被匹配,则应该放弃相应的记录。
灰常感谢这位博主的博客
http://blog.csdn.net/sinat_29278271/article/details/48081177
自己最开始写的时候完全没有如何处理无效数据的头绪。
用map<string,int>
建立车辆名与停留总时间的映射关系。主要是对录入数据的处理,对录入数据进行排序,先排车辆名,如果车名相同,时间小的排前面。当比较时,前一个数据与后一个数据,车名相同,时间不同,前一个状态为in与后一个状态为out匹配,就可以用后一个时间减前一个时间,为停留时间,加到对应的车辆名总停留时间上。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
#define MAX 10005
const int MAXRANGE = 24*60*60;
string decToTime(int time)
{
char str[20];
sprintf(str,"%02d:%02d:%02d",time/(60*60),time/60%60,time%60);
return string(str);
}
int timeToDec(int h,int m,int s)
{
return (h * 60 + m) * 60 + s;
}//转化为10进制
class Car
{
public:
string ID;
int time;
bool out;
public:
bool isMatch(const Car &c)
{
return this->ID == c.ID&& this->time < c.time && this->out == false && c.out == true;
}
bool operator <(const Car &c) const//先按车牌排序,再按时间排序
{
if (this->ID != c.ID)
{
return this->ID < c.ID;
}
else if (this->time != c.time)
{
return this->time < c.time;
}
else
{
return !this->out;
}
}
//void Printf()
//{
// cout << ID <<" "<< time <<" "<< out << endl;
// cout << decToTime(time) << endl;
//}
};
Car cars[MAX];
int sumCnt[MAXRANGE];
int main()
{
int N, K;
cin >> N >> K;
for (int i = 0; i < N; i++)
{
int h, m, s;
cin >> cars[i].ID;
scanf("%d:%d:%d",&h,&m,&s);
cars[i].time = timeToDec(h,m,s);
string status;
cin >> status;
if (status == "out")
{
cars[i].out = true;
}
else
{
cars[i].out = false;
}
}
sort(cars,cars+N);
//测试
/*for (int i = 0; i < N; i++)
{
cars[i].Printf();
}*/
map<string, int> parkTime;
int maxParkTime = -1;
for (int i = 0; i < N-1; i++)
{
if (cars[i].isMatch(cars[i+1]))//当前i状态为in,下一个i+1状态为out,满足即可进入
{
parkTime[cars[i].ID] += cars[i + 1].time - cars[i].time;
if (maxParkTime < parkTime[cars[i].ID])
{
maxParkTime = parkTime[cars[i].ID];
}
sumCnt[cars[i].time]++;
sumCnt[cars[i+1].time]--;
}
}
for (int i = 1; i < MAXRANGE; i++)
{
sumCnt[i] += sumCnt[i-1];
}
for (int i = 0; i < K; i++)
{
int h, m, s;
scanf("%d:%d:%d",&h,&m,&s);
printf("%d\n",sumCnt[timeToDec(h,m,s)]);
}
map<string, int>::iterator it;
for (it = parkTime.begin(); it != parkTime.end(); ++it)
{
if (it->second == maxParkTime)
{
cout << it->first << " ";
}
}
cout << decToTime(maxParkTime)<< endl;
system("pause");
return 0;
}