1095. Cars on Campus (30)

    考查结构体排序,需要足够细心,大致思路是先将所有记录按车牌号排序,车牌号一样按时间排序,然后将合法的记录挑选出来。在查询的时候,维护当前已经查询到何处,下一次查询从当前位置开始。查询中,如果是进的,则把当前车辆数加1,出的则减1,同时更新车辆所停靠的时间,顺便选出最长停靠时间及相关车辆。

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <functional>
#include <unordered_map>

using namespace std;

struct Record{
	char plate[10];
	int time;
	int period;
	char status;

	bool in(){
		return status == 'i';
	}

	bool out(){
		return status == 'o';
	}

	Record(char p[], int t, char s) : time(t), period(0), status(s){
		strcpy(plate, p);
	}
};

bool cmpPlate(const Record& lhs, const Record& rhs){
	return strcmp(lhs.plate, rhs.plate) < 0 
		|| (strcmp(lhs.plate, rhs.plate) == 0 && lhs.time < rhs.time);
}

bool cmpTime(const Record& lhs, const Record& rhs){
	return lhs.time < rhs.time;
}

int tosec(int hh, int mm, int ss){
	return hh*3600 + mm*60 + ss;
}

int main(){
	int n, k, hh, mm, ss;
	scanf("%d%d", &n, &k);

	vector<Record> inputs;
	for(int i = 0; i < n; ++i){
		char plate[10], status[10];
		
		scanf("%s %d:%d:%d %s", plate, &hh, &mm, &ss, status);
		inputs.emplace_back(plate, tosec(hh, mm, ss), status[0]);
	}

	sort(begin(inputs), end(inputs), cmpPlate);

	vector<Record> records;
	for(int i = 0; i+1 < (int)inputs.size(); i += 2){
		if(strcmp(inputs[i].plate, inputs[i+1].plate) == 0 
			&& inputs[i].in() && inputs[i+1].out()){

			inputs[i].period = inputs[i+1].time - inputs[i].time;
			inputs[i+1].period = inputs[i+1].time - inputs[i].time;
			records.push_back(inputs[i]);
			records.push_back(inputs[i+1]);
		}else{
			--i;
		}
	}

	sort(begin(records), end(records), cmpTime);

	int idx = 0, sum = 0, maxTime = -1;
	vector<Record> result;
	unordered_map<string, int> times;

	auto query = [&](int t){
		for(; idx < (int)records.size(); ++idx){
			if(records[idx].time > t) break;
			if(records[idx].in()){
				++sum;
			}else{
				--sum;

				string plate = records[idx].plate;
				if(times.find(plate) == times.end()){
					times.insert({plate, 0});
				}
				
				times[plate] += records[idx].period;

				if(times[plate] > maxTime){
					maxTime = times[plate];
					result = vector<Record>(1, records[idx]);
				}else if(times[plate] == maxTime){
					result.push_back(records[idx]);
				}
			}
		}
	};

	for(int i = 0; i < k; ++i){
		scanf("%d:%d:%d", &hh, &mm, &ss);
		int t = hh*3600 + mm*60 + ss;

		query(t);
		printf("%d\n", sum);
	}

	query(24*3600);

	sort(begin(result), end(result), cmpPlate);
	for(auto& r : result){
		printf("%s ", r.plate);
	}

	hh = maxTime/3600; maxTime %= 3600;
	mm = maxTime/60; maxTime %= 60;
	ss = maxTime;
	
	printf("%02d:%02d:%02d", hh, mm, ss);

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值