PAT甲级 1095 Cars on Campus (30分)

感觉这道题有一定难度呢,想要不超时,就要利用好题目里面给出的查询时间是依次递增的这一条件,转换成等价的线性关系,这样的循环就不会超时。这一步骤就是,对所有合法时间进行排序,对小于查询时间的合法时间,如果是进入,那么就加一,如果是出去,那么就减1,等合法时间大于查询时间就退出,这个停车数后面的查询时间可以累计使用。

#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
struct student{
    int time, x;
    char id[10];
}stu[10010];
struct record{
    int time, x;
}rec[10010];
bool cmp(student a, student b)
{
    if(strcmp(a.id, b.id)) return strcmp(a.id, b.id) < 0;
    else return a.time < b.time;
}
bool cmp2(record a, record b)
{
    return a.time < b.time;
}
int main()
{
    int n, k, hh, mm, ss, Max = 0, total = 0, now = 0, num = 0;
    char status[10];
    map<string, int> mp;
    scanf("%d%d", &n, &k);
    for(int i = 0; i < n; i++){
        scanf("%s%d:%d:%d%s", stu[i].id, &hh, &mm, &ss, status);
        stu[i].time = hh * 3600 + mm * 60 + ss;
        if(status[0] == 'i') stu[i].x = 0;
        else stu[i].x = 1;
    }
    sort(stu, stu + n, cmp);
    for(int i = 1; i < n; i++){
        if(strcmp(stu[i].id, stu[i - 1].id) == 0){
            if(stu[i].x == 1 && stu[i - 1].x == 0){
                rec[total].time = stu[i - 1].time, rec[total].x = 0;
                rec[total + 1].time = stu[i].time, rec[total + 1].x = 1;
                total += 2;
                if(mp.find(stu[i].id) == mp.end()) mp[stu[i].id] = stu[i].time - stu[i - 1].time;
                else mp[stu[i].id] += stu[i].time - stu[i - 1].time;
                if(mp[stu[i].id] > Max) Max = mp[stu[i].id];
            }
        }
    }
    sort(rec, rec + total, cmp2);
    for(int i = 0; i < k; i++){
        scanf("%d:%d:%d", &hh, &mm, &ss);
        int temp = hh * 3600 + mm * 60 + ss;
        while(rec[now].time <= temp && now < total){
            if(rec[now].x == 0) num++;
            else num--;
            now++;
        }
        printf("%d\n", num);
    }
    for(map<string, int>::iterator it = mp.begin(); it != mp.end(); it++){
        if(it->second == Max) printf("%s ", it->first.c_str());
    }
    printf("%02d:%02d:%02d", Max / 3600, Max % 3600 / 60, Max % 60);
    return 0;
}
发布了30 篇原创文章 · 获赞 0 · 访问量 380

猜你喜欢

转载自blog.csdn.net/qq_33942309/article/details/104485759