stl综合应用
#include <iostream>//超过1e6,不能用cin,cout,map
#include <cstring>
#include <unordered_map>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 10010;
int n, m;
struct Person//对于给相互关联的两个及以上变量时,用结构体存
{
string id;
int grade;
/*重载运算符 返回值类型 operator符号 (如果不改原数const 类名 &随意变量名name)const{
当前结构体中的变量名与name.变量名比较 类名!
}*/
bool operator< (const Person &t) const//运算符重载
{
if (grade != t.grade) return grade > t.grade;
return id < t.id;
}
}p[N];
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ ) cin >> p[i].id >> p[i].grade;
//先把信息存好 尽量别用scanf读字符串
//命令来一个处理一个,每一个命令需要的变量在{}里面定义,确保更新
for (int k = 1; k <= m; k ++ )
{
string t, c;//指令和要求
cin >> t >> c;
printf("Case %d: %s %s\n", k, t.c_str(), c.c_str());//只有printf需要c_str()
if (t == "1")
{
vector<Person> persons;
for (int i = 0; i < n; i ++ )
if (p[i].id[0] == c[0])
persons.push_back(p[i]);
sort(persons.begin(), persons.end());
if (persons.empty()) puts("NA");
else
for (auto person : persons) printf("%s %d\n", person.id.c_str(), person.grade);
}
else if (t == "2")
{
int cnt = 0, sum = 0;
for (int i = 0; i < n; i ++ )
if (p[i].id.substr(1, 3) == c)
{
cnt ++ ;
sum += p[i].grade;
}
if (!cnt) puts("NA");
else printf("%d %d\n", cnt, sum);
}
else
{
unordered_map<string, int> hash;//数据量大的时候,map会超时
for (int i = 0; i < n; i ++ )
if (p[i].id.substr(4, 6) == c)
hash[p[i].id.substr(1, 3)] ++ ;
vector<pair<int, string>> rooms;//双关键字排序,先1后2,pair只定义优先级,sort实现排序
for (auto item : hash) rooms.push_back({-item.second, item.first});
sort(rooms.begin(), rooms.end());
if (rooms.empty()) puts("NA");
else
for (auto room : rooms)
printf("%s %d\n", room.second.c_str(), -room.first);
}
}
return 0;
}