【PAT-A1095】Cars on Campus(排序的灵活应用)

【题意分析】

  • 这题技巧性比较强,而且数据量比较大,容易超时。
  • 首先冗余的不合法数据的剔除比较难进行,这题巧妙地利用排序,以车牌号字符串作为第一排序准则,将不同车辆的信息分开,每个车牌的信息再按照时间升序排列。这样就可以容易地选出成对的记录剔除无效记录。
  • 另外,就是查询部分,先将所有合法的成对记录按照时间排序,然后这里如果每个查询都遍历一次所有有效信息,那么测试点4会超时。这里可以巧妙利用查询的时间是按照时刻从小到大排序的特点,每次查询在上一次的结果上继续进行,就可以减小复杂度。

【代码】

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

struct Record
{
	string plate;
	string time;
	int ss;
	bool status;
	Record(string plate_, string time_, string status_) {
		plate = plate_;
		time = time_;
		if (status_ == "in") {
			status = true;
		}
		else if (status_ == "out")
		{
			status = false;
		}
		trans();
	}
	void trans() {
		int h = stoi(time.substr(0, 2));
		int m = stoi(time.substr(3, 2));
		int s = stoi(time.substr(6, 2));
		ss = h * 3600 + m * 60 + s;
	}
};

int trans(string time) {
	int h = stoi(time.substr(0, 2));
	int m = stoi(time.substr(3, 2));
	int s = stoi(time.substr(6, 2));
	return h * 3600 + m * 60 + s;
}

bool cmp(Record& a, Record& b) {
	if (a.plate != b.plate) return a.plate < b.plate;
	else {
		return a.ss < b.ss;
	}
}

bool cmp_on_time(Record& a, Record& b) {
	return a.ss < b.ss;
}
map<string, int> mp;

int main() {
	int n, k;
	scanf("%d %d", &n, &k);
	string plate, time, status;
	vector<Record> v, vec_valid;
	for (int i = 0; i < n; i++)
	{
		cin >> plate >> time >> status;
		v.push_back(Record(plate, time, status));
		
	}
	// 获取合法的记录
	sort(v.begin(), v.end(), cmp);

	for (int i = 0; i < v.size() - 1; i++)
	{
		if (v[i].status == true && v[i + 1].status == false && v[i].plate == v[i+1].plate) {
			vec_valid.push_back(v[i]);
			vec_valid.push_back(v[i + 1]);
		}
	}

	vector<Record> vec = vec_valid; // 复制一份;
	// 将所有合法记录按照时间排序
	sort(vec_valid.begin(), vec_valid.end(), cmp_on_time);
	string t;
	int car_num = 0, now = 0;
	for (int j = 0; j < k; j++)
	{
		cin >> t;
		int s = trans(t);
		
		while(now < vec_valid.size())
		{
			if (s >= vec_valid[now].ss) {

				if (vec_valid[now].status == true) {
					car_num++;
				}
				else
				{
					car_num--;
				}
			}
			else
			{
				break;
			}
			now++;
		}
		cout << car_num << endl;


	}
	int maxT = 0;
	for (int i = 0; i < vec.size() - 1; i += 2)
	{
		mp[vec[i].plate] += vec[i + 1].ss - vec[i].ss;
		maxT = max(maxT, mp[vec[i].plate]);
	}

	for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++)
	{
		if (it->second == maxT) {
			cout << it->first << ' ';
		}
	}

	int ts = maxT;
	printf("%02d:%02d:%02d\n", ts / 3600, ts % 3600 / 60, ts % 60);


	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值