PAT A1095(30分)

这道题对时间要求比较严格,改了很久才不超时。

先是将有效的保留后再操作,但是还是有几个测试用例超时。

于是根据题目的给的timepoint是递增的来简化遍历。才通过所有测试用例而不超时。

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805371602845696

#include 
#include 
#include 
using namespace std;
struct cars{
	char plate_number[10];
	char status[5];
	int time;
}car[10010],valid[10010];
struct record{
	char plate_number[10];
	int time;
}rec[10010];
bool cmp(cars a, cars b){
	if (strcmp(a.plate_number, b.plate_number))
		return strcmp(a.plate_number, b.plate_number) < 0;
	else if(a.time != b.time)
		return a.time < b.time;
	else
		return strcmp(a.status, b.status) < 0;
}
bool cmp2(record a, record b){
	if(a.time != b.time)
		return a.time > b.time;
	else
		return strcmp(a.plate_number, b.plate_number) < 0;
}
bool cmp3(cars a, cars b){
	return a.time < b.time;
}
int main(){
	int n, k;
	scanf("%d%d", &n, &k);
	int hh, mm, ss, time;
	for(int i = 0; i < n; i++){
		scanf("%s %d:%d:%d %s", car[i].plate_number, &hh, &mm, &ss, car[i].status);
		car[i].time = hh * 3600 + mm * 60 + ss;
	}
	sort(car, car + n, cmp);
	int carnum = 0;
	for(int j = 1; j < n; j++){
		if (!strcmp(car[j].plate_number, car[j-1].plate_number) && !strcmp(car[j].status, "out") && !strcmp(car[j-1].status, "in")){
			valid[carnum++] = car[j-1];
			valid[carnum++] = car[j];
		}
	}
	int num = 0;
	for(int j = 1; j < carnum; j += 2){
		if(!num){
			strcpy(rec[num].plate_number, valid[j].plate_number);
			num++;
		}
		else if(strcmp(rec[num-1].plate_number, valid[j].plate_number)){
			strcpy(rec[num].plate_number, valid[j].plate_number);
			num++;
		}
		time = valid[j-1].time;
		while(time < valid[j].time){
			time++;
			rec[num-1].time++;
		}
	}
	sort(rec, rec + num, cmp2);

	sort(valid, valid + carnum, cmp3);
	int now = 0;
	num = 0;
	for(int i = 0; i < k; i++){
		scanf("%d:%d:%d", &hh, &mm, &ss);
		time = hh * 3600 + mm * 60 + ss;
		for(; now < carnum && valid[now].time <= time; now++){
			if(!strcmp(valid[now].status, "in"))
				num++;
			else
				num--;
		}
		printf("%d\n", num);
	}
	printf("%s", rec[0].plate_number);
	for(int i = 1; rec[i].time == rec[0].time; i++)
		printf(" %s", rec[i].plate_number);
	hh = rec[0].time / 3600;
	mm = rec[0].time % 3600 / 60;
	ss = rec[0].time % 3600 % 60;
	printf(" %02d:%02d:%02d\n", hh, mm, ss);
	return 0;
}

 

你可能感兴趣的:(PAT)