当前位置: 代码迷 >> 综合 >> pat 甲级 1012 The Best Rank(25)
  详细解决方案

pat 甲级 1012 The Best Rank(25)

热度:52   发布时间:2023-12-14 23:20:41.0

这道题其实没多大意思,就是求最好排名并把最好排名以及这个排名对应的字母输出,这题就结束了。我的话主要思路是这样的,把每个人每一科的成绩排名都求出,而要求排名,那首先需要先按照成绩排序,直接调用sort函数就行了,排完序再求排名,这个地方有个要注意的点就是某一科同分的人的那个科目的排名是一样的。代码有点小啰嗦,但其实不复杂,就是排序+排名那块再加上最后输出结果的时候做逻辑判断那块有一些啰嗦的代码,照例,代码还是附上以供参考:

#include<iostream>
#include<vector>
#include <string>
#include<algorithm>
using namespace std;
struct Node    //每条记录的结构体
{string ID;int C;int M;int E;int A;int ARank;int CRank;int MRank;int ERank;
};
bool compareByA(Node a, Node b)  //用于对A项降序排序,以下同理
{return a.A > b.A;
}
bool compareByC(Node a, Node b)
{return a.C > b.C;
}
bool compareByM(Node a, Node b)
{return a.M > b.M;
}
bool compareByE(Node a, Node b)
{return a.E > b.E;
}
int main()
{int m, n;cin >> m >> n;vector<Node> arr(m);vector<string> arr2(n);for (int i = 0; i < m; i++){cin >> arr[i].ID;cin >> arr[i].C;cin >> arr[i].M;cin >> arr[i].E;arr[i].A= (arr[i].C+ arr[i].M+ arr[i].E+1.5)/3;  //四舍五入计算平均值A}for (int i = 0; i < n; i++){cin >> arr2[i];}sort(arr.begin(),arr.end(),compareByA);for (int i = 0; i < m; i++)  //对A项赋予排名{if (i!=0){if (arr[i - 1].A == arr[i].A){arr[i].ARank = arr[i - 1].ARank;}else{arr[i].ARank = i + 1;}}else{arr[i].ARank = i + 1;}}sort(arr.begin(), arr.end(), compareByC);for (int i = 0; i < m; i++)  //对C科目赋予排名{if (i != 0){if (arr[i - 1].C == arr[i].C){arr[i].CRank = arr[i - 1].CRank;}else{arr[i].CRank = i + 1;}}else{arr[i].CRank = i + 1;}}sort(arr.begin(), arr.end(), compareByM);for (int i = 0; i < m; i++)   //对M科目赋予排名{if (i != 0){if (arr[i - 1].M == arr[i].M){arr[i].MRank = arr[i - 1].MRank;}else{arr[i].MRank = i + 1;}}else{arr[i].MRank = i + 1;}}sort(arr.begin(), arr.end(), compareByE);for (int i = 0; i < m; i++)  //对E科目赋予排名{if (i != 0){if (arr[i - 1].E == arr[i].E){arr[i].ERank = arr[i - 1].ERank;}else{arr[i].ERank = i + 1;}}else{arr[i].ERank = i + 1;}}for (int i = 0; i < n; i++)  //输出结果{int flag = 0;      //用于判断该编号是否存在于评分表上for (int j = 0; j < m; j++){if (arr[j].ID == arr2[i])  //若存在,则进入该逻辑{flag++;int min =9999;  //用于记录最好排名int index = 0;  //用于记录最好排名对应的字母if (min > arr[j].ARank){min = arr[j].ARank;index = 1;}if (min>arr[j].CRank){min = arr[j].CRank;index = 2;}if (min > arr[j].MRank){min = arr[j].MRank;index = 3;}if (min > arr[j].ERank){min = arr[j].ERank;index = 4;}if (index == 1){cout << arr[j].ARank << " " << "A"<<endl;}else if (index == 2){cout << arr[j].CRank << " " << "C" << endl;}else if (index == 3){cout << arr[j].MRank << " " << "M" << endl;}else if (index == 4){cout << arr[j].ERank << " " << "E" << endl;}break;}}if (flag == 0)  //不存在则输出N/A{cout << "N/A" << endl;}}system("pause");return 0;
}