1095 解码PAT准考证 (25分)

1 题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2 思路

本题考查字符串处理和结构体排序,关键点如下:

  1. 采用vector存储结构体数据
  2. 指令1和指令3的排序是一样的,可以复用
  3. 指令3,采用unordered_map存储考场编号和总人数,并且可以避免超时。Tip:map底层采用的是红黑树,有序的,可以采用中序遍历从小到大遍历出来,但是运行时间长;unordered_map采用的是散列哈希,内存空间大,但是时间复杂度为O(1)

思路参考柳婼的博客,特此感谢。

3 代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
struct node{
    string id;
    int value;
};
bool cmp(const node &a,const node &b){
    return a.value == b.value ? a.id < b.id : a.value > b.value;
}

int main(){
    int n,m;
    cin>> n >> m;
    vector<node> v(n);
    for(int i =0;i < n;i++){
        cin>> v[i].id >> v[i].value;
    }
    for(int i =0;i < m;i++){
        int type, cnt = 0, sum =0;
        string s;
        cin>> type >> s;
        printf("Case %d: %d %s\n",i + 1,type,s.c_str());
        vector<node> ans;
        if(type == 1){
            for(int j=0;j < n;j++){
                if(v[j].id[0] == s[0]){
                    ans.push_back(v[j]);
                }
            }
        }else if(type == 2){
            for(int j=0;j < n;j++){
                if(v[j].id.substr(1,3) == s){
                    cnt ++;
                    sum += v[j].value;
                }
            }
            if(cnt != 0){
                printf("%d %d\n", cnt, sum);
            }
        }else if(type == 3){
            unordered_map <string,int> m;
            for(int j=0;j < n;j++){
                if(v[j].id.substr(4,6) == s){
                    m[v[j].id.substr(1,3)]++;
                }
            }
            for(auto it: m){
                ans.push_back({it.first, it.second});
            }
        }
        sort(ans.begin(), ans.end(),cmp);
        for(auto k : ans){
            printf("%s %d\n", k.id.c_str(), k.value);
        }
        if((cnt == 0 && type == 2) || ((type == 1 || type == 3) && ans.size() == 0)){
            printf("NA\n");
        }
    }
    system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值