其他分享
首页 > 其他分享> > 1095 解码PAT准考证 (25 分)

1095 解码PAT准考证 (25 分)

作者:互联网

原题

https://pintia.cn/problem-sets/994805260223102976/problems/1071786104348536832

知识点

之前没用过<unordered_map>抄答案都有点费劲。https://blog.csdn.net/weixin_45003868/article/details/118196370

#include<unordered_map>
unordered_map<int, int> map;
//使用“数组”形式插入
map[2] = 200;
//迭代
for (auto &x : map) {
  cout << x.first << " " << x.second << endl;//取出键和值
}

首先结构体的的排序用得妙——类型一和类型三要求绑定在一起两个数据,既要正向排序然后反向排序。
string::c_str()string类型调用后可以用,printf("%s")输出
&与变量声明一起使用代表这个变量是引用没办法赋值常量),类似java和python的引用类型变量和基本类型变量区别。这两种语言中没有指针怎么实现传址,就是利用引用。

代码

代码基本是抄的柳大佬的:

#include <iostream>
#include <algorithm>
#include<string>
#include<vector>
#include<unordered_map>
using namespace std;

struct Examinee{
    string id;
    int grade;
};
bool cmp(const Examinee &a,const Examinee &b){//&符号代表c++引用,可不加
    //注意相等的情况
    return a.grade!=b.grade?a.grade>b.grade:a.id<b.id;//按其准考证号的字典序递增输出
}

int main(void){
    int n,m;
    cin >> n >> m;
    vector<Examinee> e(n);
    for(int i=0;i<n;i++) cin >> e[i].id>>e[i].grade;

    int type;    
    string require;
    for (int i = 0; i < m; i++)
    {        
        cin >> type>>require;
        printf("Case %d: %d %s\n",i+1,type,require.c_str());

        bool flag=true;
        if(type==1){
            sort(e.begin(),e.end(),cmp);
            for(int j = 0; j <n;j++)
            if(e[j].id[0]==require[0]){
                printf("%s %d\n",e[j].id.c_str(),e[j].grade);
                flag=false;
            } 
        }else if(type==2){
            int cnt=0,sum=0;
            for(int j = 0; j <n;j++)
            if(e[j].id.substr(1,3)==require){
                cnt++;
                sum+=e[j].grade;
                flag=false;
            }
            if(cnt!=0) printf("%d %d\n",cnt,sum);
        }else if(type==3){
            vector<Examinee> temp;
            unordered_map<string,int> map;
            for(int j = 0; j <n;j++)
                if(e[j].id.substr(4,6)==require){
                    map[e[j].id.substr(1,3)]++;
                    flag=false;
                }
            for(auto it:map) temp.push_back({it.first,it.second});//把map值,放入结构体
            sort(temp.begin(), temp.end(),cmp);
            for(int i=0; i<temp.size(); i++)
                printf("%s %d\n",temp[i].id.c_str(),temp[i].grade);
        }

        if(flag) printf("NA\n");
    }   
    return 0;
}

标签:1095,PAT,string,map,grade,int,25,include,type
来源: https://www.cnblogs.com/InifiteVictory/p/15700083.html