A1153 Decode Registration Card of PAT (25分)

一、技术总结

  1. 本题没有数据结构的具体知识,但是考查逻辑,也就按照题目中的要求进行运算最后输出结果;
  2. 但是处理的方式显得很重要,一个要点是,对于对于这种题目最好是将结果全部储存,然后再按需进行重新查询;
  3. 如果存在超时可以使用unordered_map;同时在编写排序算法的时候,cmp传参可以使用引用,这样可以提快速度;

二、参考代码

#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
using namespace std;
struct node{
	string s;
	int score;
};
bool cmp(node &a, node &b){
	if(a.score != b.score) return a.score > b.score;
	else return a.s < b.s;
}
int main(){
	int n, m;
	cin >> n >> m;
	vector<node> v;
	for(int i = 0; i < n; i++){
		string str;
		int num;
		cin >> str >> num;
		v.push_back(node{str, num});
	}
	int a;
	string str2;
	for(int i = 1; i <= m; i++){
		cin >> a >> str2;
		printf("Case %d: %d %s\n", i, a, str2.c_str());
		vector<node> ans;
		int cnt = 0, sum = 0; //用于查询2的人数统计以及分数总和统计
		if(a == 1){
			for(int j = 0; j < n; j++){
				if(v[j].s[0] == str2[0]) ans.push_back(v[j]);
			}
		}else if(a == 2){
			for(int j = 0; j < n; j++){
				if(v[j].s.substr(1, 3) == str2){
					cnt++;
					sum += v[j].score;
				}
			}
			if(cnt != 0) printf("%d %d\n", cnt, sum);
		}else if(a == 3){
			unordered_map<string, int> m;
			for(int j = 0; j < n; j++){
				if(v[j].s.substr(4, 6) == str2) m[v[j].s.substr(1, 3)]++;
			}
			for(auto it = m.begin(); it != m.end(); it++) ans.push_back({it->first, it->second});
		}
		sort(ans.begin(), ans.end(), cmp);
		for(int j = 0; j < ans.size(); j++){
			printf("%s %d\n", ans[j].s.c_str(), ans[j].score);
		}
		if(((a == 1 || a == 3) && ans.size() == 0) || (a == 2 && cnt == 0)) printf("NA\n");
	}
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/tsruixi/p/13193164.html