PTA甲级考试真题练习95——1095 Cars on Campus

题目

在这里插入图片描述

思路

先使用map排序后求出每个车子进出的时间,使用hash数组存储每个点车辆数,然后使用树状数组记录车子的时间后,查询即可

代码

#include <iostream>
#include <vector>
#include <unordered_map>
#include<string>
#include<algorithm>
#include<set>
#define lowbit(x) ((x)&(-x))
using namespace std;
const int nmax =86405;
int timeA[nmax];
struct Info {
	int time;
	int mark;  //in为0,out为1
	bool operator < (const Info& a) const {
		return time < a.time;
	}
};

int  getSum(int x) {
	int sum = 0;
	for (int i = x; i < nmax; i += lowbit(i)) 
		sum += timeA[i];
	return sum;
}

void update(int x, int v) {
	for (int i = x; i > 0; i -= lowbit(i)) 
		timeA[i] += v;
}

typedef struct {
	int time;
	string ID;
}order;
vector<order> vec;
unordered_map<string, set<Info>> m;
int n,qn;



bool cmp(const order& a, const order& b) {
	if (a.time != b.time)
		return a.time > b.time;
	else
		return a.ID < b.ID;
}

int main()
{
	cin >> n >> qn;
	int ans = 0;
	for (int i = 0; i < n; ++i) {
		string ID,mark;
		int hour, minute, second;
		cin >> ID;
		scanf("%d:%d:%d", &hour, &minute, &second);
		cin >> mark;
		Info info;
		if (mark == "in")
			info = { hour * 3600 + minute * 60 + second,0 };
		else
			info = { hour * 3600 + minute * 60 + second,1 };
		auto p = m.find(ID);
		if (p != m.end()) {
			p->second.insert(info);
		}
		else {
			set<Info> s;
			s.insert(info);
			m.insert(pair<string, set<Info>>(ID, s));
		}
	}
	memset(timeA, 0, sizeof(timeA));
	for (auto& p : m) {
		int maxTime = 0;
		for (auto q = p.second.begin(); q != p.second.end();++q) {
			auto k = q++;
			if (q == p.second.end())
				break;
			if (k->mark == 0 && q->mark == 1) {
				//查询数组加1
				update(q->time, 1);
				update(k->time, -1);
				maxTime += q->time - k->time;
			}
			q = k;
		}
		if (maxTime >= ans) {
			ans = maxTime;
			order o = { maxTime,p.first };
			vec.emplace_back(o);
		}
	}
	for (int i = 0; i < qn; ++i) {
		int hour, minute, second;
		scanf("%d:%d:%d", &hour, &minute, &second);
		cout << getSum(hour * 3600 + minute*60 + second + 1)<<endl;
	}
	sort(vec.begin(), vec.end(), cmp);
	int t = vec[0].time;
	cout << vec[0].ID;
	for (int i = 1; i < vec.size(); ++i) {
		if (vec[i].time != t)
			break;
		cout << " " << vec[i].ID;
	}
	int hour, minute, second;
	hour = t / 3600;
	minute = t % 3600 / 60;
	second = t % 3600 % 60;
	printf(" %02d:%02d:%02d", hour, minute, second);
	return 0;
}
发布了153 篇原创文章 · 获赞 4 · 访问量 3799

猜你喜欢

转载自blog.csdn.net/qq_43647628/article/details/105430641