1095 解码PAT准考证 (25 分)

题干戳我

分析:

此题太拐了,不仅步骤上拐,耗时上也拐...

感谢柳婼大神~

代码:

#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
#include<unordered_map>
using namespace std;
struct student{
	string s;
	int score;
};
struct site{
	string siteid;
	int cnt;
};
//排序传参建议用引用传参,这样更快(student &a,student &b)
bool cmp1(student a,student b){
	if(a.score==b.score)
		return a.s<b.s;
	return a.score>b.score;
}
bool cmp2(site a,site b){
	if(a.cnt==b.cnt) return a.siteid<b.siteid;
	return a.cnt > b.cnt;
}
int main(){
	int n,m;
	scanf("%d %d",&n,&m);
	student stu[n];
	for(int i=0;i<n;i++)
		cin>> stu[i].s >>stu[i].score;
	for(int i=1;i<=m;i++){
		int k;
		scanf("%d",&k);
		if(k==1){
			char grade;
			scanf(" %c",&grade);//注意%c前面有一个空格 
			printf("Case %d: %d %c\n",i,k,grade);
			vector<student> ans;
			for(int j=0;j<n;j++)
				if(stu[j].s[0]==grade) ans.push_back(stu[j]);
			sort(ans.begin(),ans.end(),cmp1);
			for(int j=0;j<ans.size();j++)
				printf("%s %d\n", ans[j].s.c_str(), ans[j].score);
			if (ans.size() == 0) printf("NA\n");
		} 
		else if(k==2){
			string siteid;
			cin>>siteid;  /*string类型不可以使用scanf("%s")输入!!!*/ 
			printf("Case %d: %d %s\n",i,k,siteid.c_str());
			int cnt=0,sumscore=0;
			for(int j=0;j<n;j++){
				string sitestr=stu[j].s.substr(1,3);
				if(siteid==sitestr){
					cnt++;
					sumscore+=stu[j].score;
				} 
			}
			if(cnt) printf("%d %d\n",cnt,sumscore); 
			else printf("NA\n");
		}else{//4~9位 时间 
			string date;
			cin>>date;
			printf("Case %d: %d %s\n",i,k,date.c_str());
			unordered_map<string,int> m;
			for(int j=0;j<n;j++)
				if(stu[j].s.substr(4,6)==date)
					m[stu[j].s.substr(1,3)]++;
			vector<site> ans;
			for (auto it : m)
				ans.push_back({it.first, it.second});//这里注意,学到了!
			if(!ans.size()) printf("NA\n");
			else{
				sort(ans.begin(),ans.end(),cmp2);
				for(int j=0;j<ans.size();j++)
					printf("%s %d\n",ans[j].siteid.c_str(),ans[j].cnt);
			}
		}
	}
	return 0;
}

*  scanf(" %c",&grade);   // 注意%c前面有一个空格 

scanf()读取单个字符的时候,如果上面的语句也有scanf, 可能会读入换行符,导致读取的字符不是自己写入的字符。

如果用scanf("%c",&ch),那么程序不会忽略为了输入而按下的回车键操作,而是认为回车键是后续操作而继续响应;

scanf(" %c", &ch)在%c之前空格会告诉scanf忽略前面的空行,而等待第一个非空行元素读入其中。这样就能避免问题的出现。 

 for (auto it : m)   //C++11新特性
     ans.push_back({it.first, it.second}); // 这里注意,学到了!

把map中的键值对赋值到struct vector中~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值