PAT成长之路——乙级1095 解码PAT准考证 (25 分)

1095 解码PAT准考证 (25 分)
PAT 准考证号由 4 部分组成:
第 1 位是级别,即 T 代表顶级;A 代表甲级;B 代表乙级;
第 2~4 位是考场编号,范围从 101 到 999;
第 5~10 位是考试日期,格式为年、月、日顺次各占 2 位;
最后 11~13 位是考生编号,范围从 000 到 999。
现给定一系列考生的准考证号和他们的成绩,请你按照要求输出各种统计信息。
输入格式:
输入首先在一行中给出两个正整数 N(≤10
​4
​​ )和 M(≤100),分别为考生人数和统计要求的个数。
接下来 N 行,每行给出一个考生的准考证号和其分数(在区间 [0,100] 内的整数),其间以空格分隔。
考生信息之后,再给出 M 行,每行给出一个统计要求,格式为:类型 指令,其中
类型 为 1 表示要求按分数非升序输出某个指定级别的考生的成绩,对应的 指令 则给出代表指定级别的字母;
类型 为 2 表示要求将某指定考场的考生人数和总分统计输出,对应的 指令 则给出指定考场的编号;
类型 为 3 表示要求将某指定日期的考生人数分考场统计输出,对应的 指令 则给出指定日期,格式与准考证上日期相同。
输出格式:
对每项统计要求,首先在一行中输出 Case #: 要求,其中 # 是该项要求的编号,从 1 开始;要求 即复制输入给出的要求。随后输出相应的统计结果:
类型 为 1 的指令,输出格式与输入的考生信息格式相同,即 准考证号 成绩。对于分数并列的考生,按其准考证号的字典序递增输出(题目保证无重复准考证号);
类型 为 2 的指令,按 人数 总分 的格式输出;
类型 为 3 的指令,输出按人数非递增顺序,格式为 考场编号 总人数。若人数并列则按考场编号递增顺序输出。
如果查询结果为空,则输出 NA。
输入样例:
8 4
B123180908127 99
B102180908003 86
A112180318002 98
T107150310127 62
A107180908108 100
T123180908010 78
B112160918035 88
A107180908021 98
1 A
2 107
3 180908
2 999
输出样例:
Case 1: 1 A
A107180908108 100
A107180908021 98
A112180318002 98
Case 2: 2 107
3 260
Case 3: 3 180908
107 2
123 2
102 1
Case 4: 2 999
NA


分析:(分析有参考柳诺大神的部分,顺谢柳神)
1、本题是一个成绩统计的常规题目,主要是数据存储以及避免超时。
2、测试点4(查询3)超时需要注意的几个点:
①如果用容器(容器用的多了可能会超时),尽量只在查询3的时候用,而且如果用map的话要用unordered_map,不然会超时(多耗时)。
②输出string用printf, 尽量不要用cout.

③传参数的时候养成用引用传参的方式,尤其是在写compare函数的时候,以便减少时间损耗。

代码:

#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>//注意点①
#include <algorithm>
using namespace std;
typedef pair<string, int> PAIR;
struct stu
{
    string inf;
    int score;
}test[10000], temp[10000];
bool compare1(stu& a, stu& b)//注意点③
{
    return a.score != b.score ? a.score > b.score : a.inf < b.inf;
}
bool compare2(PAIR& a, PAIR& b)//注意点③
{
    return a.second != b.second ? a.second > b.second : a.first < b.first;
}
int main()
{
    int N, M;
    int i, j, k;
    scanf("%d%d", &N, &M);
    for(i = 0; i < N; i++) cin >> test[i].inf >> test[i].score;
    int dir;
    string range;
    int num, sscore;
    for(i = 0; i < M; i++)
    {
        cin >> dir >> range;
        printf("Case %d: %d %s\n", i + 1, dir, range.c_str());//注意点②
        if(dir == 1)//question1
        {
            for(j = 0, k = 0; j < N; j++)
                if(test[j].inf[0] == range[0])
                    temp[k++] = test[j];
            if(!k) printf("NA\n");
            else
            {
                sort(temp, temp + k, compare1);
                for(j = 0; j < k; j++) printf("%s %d\n", temp[j].inf.c_str(), temp[j].score);
            }
        }
        else if(dir == 2)//question 2
        {
            num = 0;
            sscore = 0;
            for(j = 0; j < N; j++)
                if(test[j].inf.substr(1, 3) == range)
                    num++, sscore += test[j].score;
            if(!num) printf("NA\n");
            else printf("%d %d\n", num, sscore);
        }
        else//question 3
        {
            unordered_map<string, int> m;
            for(j = 0; j < N; j++)
                if(test[j].inf.substr(4, 6) == range)//if this is the date we need
                    m[test[j].inf.substr(1, 3)]++;//increase the number of the certain classroom
            vector<PAIR> vec(m.begin(), m.end());
            if(!vec.size()) printf("NA\n");
            else
            {
                sort(vec.begin(), vec.end(), compare2);
                for(j = 0; j < vec.size(); j++) printf("%s %d\n", vec[j].first.c_str(), vec[j].second);
            }
        }
    }
    return 0;
}


PS:用cout超时,用map超时,不用引用传参时间从当前的140ms左右变成180ms左右。
(多谢阅读)

### PAT 1095 解码准考证 测试点4 超时优化 针对PAT乙级真题中的 `1095 解码PAT准考证` 的测试点4超时问题,可以通过以下策略来优化算法性能。 #### 数据存储与处理优化 为了减少不必要的重复计算并提高效率,在数据读取阶段可以预先解析准考证号的信息,并将其类存储到合适的数据结构中。例如,对于不同类型的查询需求(按等级、考场号或日期),可别构建对应的哈希表或其他索引结构以便快速查找[^1]。 ```python from collections import defaultdict def preprocess(records): level_map = defaultdict(list) room_map = defaultdict(lambda: {'count': 0, 'total_score': 0}) date_map = defaultdict(dict) for record in records: id_, score = record.split() level, room_id, exam_date, _ = decode_pat_id(id_) # 构建level_map用于查询一 level_map[level].append((id_, int(score))) # 更新room_map用于查询二 room_key = f"{level}-{room_id}" if room_key not in room_map: room_map[room_key]['students'] = [] room_map[room_key]['students'].append(int(score)) room_map[room_key]['count'] += 1 room_map[room_key]['total_score'] += int(score) # 构建date_map用于查询三 if exam_date not in date_map[level]: date_map[level][exam_date] = {} if room_id not in date_map[level][exam_date]: date_map[level][exam_date][room_id] = { 'count': 0, 'total_score': 0 } date_map[level][exam_date][room_id]['count'] += 1 date_map[level][exam_date][room_id]['total_score'] += int(score) return level_map, room_map, date_map ``` 上述代码展示了如何预处理输入记录以支持高效的多维度查询操作[^2]。 #### 查询逻辑调整 在实现具体查询功能时,应充利用已建立的映射关系而非重新遍历原始数据集。这样能够显著降低时间复杂度至接近O(1)级别[^3]。 ##### 查询一:按等级筛选考生 当接收到指定考试级别的请求时,只需访问对应键值下的列表即可完成排序输出任务。 ```python def query_level(level_map, target_level): candidates = sorted( [(sid, sc) for sid, sc in level_map[target_level]], key=lambda x: (-x[1], x[0]) ) result = "\n".join([f"{cand[0]} {cand[1]}" for cand in candidates]) or "NA" return result ``` ##### 查询二:统计特定考场信息 利用事先准备好的房间字典可以直接获取所需统计数据。 ```python def query_room(room_map, target_room): prefix = "-".join(target_room[:2]) stats = room_map.get(prefix, {}) count = sum(len(stats['students'])) total_scores = sum(stats['students']) avg_score = round(total_scores / max(count, 1)) if count != 0 else 0 output_lines = [ str(count), str(total_scores), *[str(scr) for scr in sorted(stats['students'])], str(avg_score) ] return '\n'.join(output_lines) if count > 0 else "NA" ``` ##### 查询三:汇总某日各场次情况 依据先前整理过的日期关联资料执行相应运算流程。 ```python def query_date(date_map, target_date_info): lvl, dt = target_date_info rooms_data = list(date_map[lvl][dt].items()) ordered_rooms = sorted( rooms_data, key=lambda item: (-item[1]['count'], item[0]) ) lines = [" ".join([ rm_no, str(info['count']), str(info['total_score']) ]) for rm_no, info in ordered_rooms] final_output = "\n".join(lines) if lines else "NA" return final_output ``` 以上函数均基于前期精心设计的数据组织形式运作,从而有效规避了因逐条扫描带来的额外开销问题^.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值