C++ 代码
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
struct Record {
int time;
bool isIn;
bool operator <(const Record& b) const {
return time < b.time;
}
};
unordered_map<string, vector<Record>> car;
int main() {
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++) {
char id[8], type[4];
int hh, mm, ss;
scanf("%s %d:%d:%d %s", id, &hh, &mm, &ss, type);
int time = hh * 60 * 60 + mm * 60 + ss;
bool flag = false;
if (type[0] == 'i') {
flag = true;
}
car[id].push_back({ time, flag });
}
int maxTime = 0;
vector<string> resCar;
vector<Record> vaild;
for (auto& item : car) {
auto& record = item.second;
// 根据时间递增排序
sort(record.begin(), record.end());
int parkTime = 0;
// 记录有效记录
for (int i = 0; i < record.size(); i++) {
if (record[i].isIn) {
if (i + 1 < record.size() && record[i + 1].isIn == false) {
vaild.push_back(record[i]);
vaild.push_back(record[i + 1]);
parkTime += record[i + 1].time - record[i].time;
i++;
}
}
}
// 更新最长停车时间
if (parkTime > maxTime) {
maxTime = parkTime;
resCar.clear();
resCar.push_back(item.first);
}
else if (parkTime == maxTime) {
resCar.push_back(item.first);
}
}
// 有效记录根据时间递增排序
sort(vaild.begin(), vaild.end());
// 因为查询时间也是递增的,不需要每次重新遍历
int cnt = 0;
int idx = 0;
for (int i = 0; i < k; i++) {
int hh, mm, ss;
scanf("%d:%d:%d", &hh, &mm, &ss);
int queryTime = hh * 60 * 60 + mm * 60 + ss;
for(; idx < vaild.size(); idx++) {
if(vaild[idx].time <= queryTime) {
if(vaild[idx].isIn) cnt++;
else cnt--;
} else break;
}
printf("%d\n", cnt);
}
// 将停车最久的ID根据字母序排序
sort(resCar.begin(), resCar.end());
for (int i = 0; i < resCar.size(); i++) {
printf("%s ", resCar[i].c_str());
}
printf("%02d:%02d:%02d\n", maxTime / 3600, maxTime % 3600 / 60, maxTime % 60);
return 0;
}
好牛!
看完大佬的 数据结构功底 特别是看到indx不需要更新 太强了!