PAT题解——1012. The Best Rank (25)
2017-08-05 11:48
381 查看
[声明]:由于本人在使用《算法笔记》的过程中有部分题解和《算法笔记》上的解法不同,特此作为记录,同时可以提供新的思路供读者参考;
题目链接:https://www.patest.cn/contests/pat-a-practise/1012
解题思路:
① 为了找到最好的排名,每个学生设置一个包含各个科目排名的数组rank[4],从而可以找到最小排名的科目;又由于最小排名相同时有科目的优先级,所以这个排名数组所代表的科目顺序也按照优先级来,即排名数组中表示的排名依次是科目A、C、M、E;
② 同时每个学生的结构体中用一个符合优先级顺序的grade[4]数组来记录各科成绩,这样使用一个cmp函数结合for循环就可以完成各个科目排名的排序;
③ 使用Min函数找出优先级条件下最小排名的科目的下标;从而按要求输出;
AC代码:
题目链接:https://www.patest.cn/contests/pat-a-practise/1012
解题思路:
① 为了找到最好的排名,每个学生设置一个包含各个科目排名的数组rank[4],从而可以找到最小排名的科目;又由于最小排名相同时有科目的优先级,所以这个排名数组所代表的科目顺序也按照优先级来,即排名数组中表示的排名依次是科目A、C、M、E;
② 同时每个学生的结构体中用一个符合优先级顺序的grade[4]数组来记录各科成绩,这样使用一个cmp函数结合for循环就可以完成各个科目排名的排序;
③ 使用Min函数找出优先级条件下最小排名的科目的下标;从而按要求输出;
AC代码:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct s{ char id[10]; int grade[4]; //依次在A C M E上的成绩 int rank[4]; //依次在A C M E上的排名 }stu[2010]; char subj[4]={'A','C','M','E'}; //按照优先级排序 int min(int a[]){ //找到最小的排名 int m=0; for(int i=1;i<4;i++){ if(a[i]<a[m])m=i; //由于对应的科目正好是优先级A C M E } //所以排名相等的情况下将找到优先级最高的科目的排名 return m; //返回排名最小的科目的下标 } int n; bool cmp(s a,s b){ return a.grade >b.grade ; //用一个cmp函数进行4门科目的排名,n取0-3 } int main(){ int N,M; scanf("%d%d",&N,&M); for(int i=0;i<N;i++){ scanf("%s %d %d %d",stu[i].id,&stu[i].grade[1],&stu[i].grade[2],&stu[i].grade[3]); stu[i].grade[0]=stu[i].grade[1]+stu[i].grade[2]+stu[i].grade[3]; //平均分的排名直接用总分进行 } for(n=0;n<4;n++){ sort(stu,stu+N,cmp); //用n取0-3来对4门科目依次进行培明 stu[0].rank =1; //将第一名设置为1 for(int j=1;j<N;j++){ if(stu[j].grade ==stu[j-1].grade ) stu[j].rank =stu[j-1].rank ; //如果该科目成绩与前一名相同 ,则排名相同 else stu[j].rank =j+1; //分数与前一名不同,则序号加1 } } char cha[20]; int j; for(int i=0;i<M;i++){ scanf("%s",cha); //查询的id for(j=0;j<N;j++){ if(!strcmp(stu[j].id,cha)){ //找到这个id int m=min(stu[j].rank); //调用Min函数找到科目优先级的条件下的最小名次的科目的下标 printf("%d %c\n",stu[j].rank[m],subj[m]); //输出最小排名和对应科目 break; //如果找到要查询的id跳出循环 } } if(j==N)printf("N/A\n"); // 没有要查询的ID } }
相关文章推荐
- PAT 甲级1012. The Best Rank (25)
- PAT 1012. The Best Rank (25)
- PAT 1012 The Best Rank (25)
- 【c++】PAT (Advanced Level)1012. The Best Rank (25)*
- PAT(甲级) 1012. The Best Rank (25)
- PAT 1012. The Best Rank (25)
- PAT 1012. The Best Rank (25)
- PAT (Advanced) 1012. The Best Rank (25)
- PAT 1012. The Best Rank (25)
- PAT 1012. The Best Rank (25)
- PAT:A1012. The Best Rank (0/25)
- PAT 1012. The Best Rank (25) 未通过,段错误
- PAT (Advanced Level) 1012. The Best Rank (25)
- PAT 甲级 1012. The Best Rank (25)
- PAT1012. The Best Rank (25)
- PAT甲级 1012. The Best Rank (25)
- PAT甲级-1012. The Best Rank (25)并列排序
- PAT甲级真题1012. The Best Rank (25)
- PAT 1012. The Best Rank (25) 一定范围的整数值排序
- [PAT]1012. The Best Rank (25)