PAT 1012 The Best Rank
暴力、打表(记忆已经查询过的学号对应的排名,防止反复查询同一学号)
因为题目中已经规定学号是6位数,所以用int表示方便打表。
1 #include <iostream> 2 #include <stdio.h> 3 #include <string> 4 #include <algorithm> 5 6 using namespace std; 7 8 int n, m; 9 struct Student 10 { 11 int id; 12 int C; 13 int M; 14 int E; 15 int A; 16 }stu[2010]; 17 18 // 内置函数有rank,所以这里不起名为rank 19 // 打表 20 int rank1[1000000]; //排名最高时候的名次 21 char rank2[1000000]; //排名最高对应的科目 22 23 24 int getMin(int a, int b, int c, int d) 25 { 26 int Min = a; 27 Min = min(Min, b); 28 Min = min(Min, c); 29 Min = min(Min, d); 30 31 return Min; 32 } 33 34 35 int main() 36 { 37 cin >> n >> m; 38 for(int i = 1; i <= n; ++i) 39 { 40 scanf("%d%d%d%d", &stu[i].id, &stu[i].C, &stu[i].M, &stu[i].E); 41 stu[i].A = (stu[i].C + stu[i].M + stu[i].E) / 3; 42 } 43 44 for(int k = 1; k <= m; ++k) 45 { 46 int sid; //待查找排名的学生的学号 47 scanf("%d", &sid); 48 if(rank1[sid] != 0) 49 { 50 if(k != m) 51 cout << rank1[sid] << ' ' << rank2[sid] << endl; 52 else 53 cout << rank1[sid] << ' ' << rank2[sid]; 54 continue; 55 } 56 57 int curScoreA = -1; 58 int curScoreC = -1; 59 int curScoreM = -1; 60 int curScoreE = -1; 61 62 int curRankA = 1; 63 int curRankC = 1; 64 int curRankM = 1; 65 int curRankE = 1; 66 67 int curRank = -1; 68 char curRankSubject = 'A'; 69 70 for(int i = 1; i <= n; ++i) 71 { 72 if(stu[i].id == sid) 73 { 74 curScoreA = stu[i].A; 75 curScoreC = stu[i].C; 76 curScoreM = stu[i].M; 77 curScoreE = stu[i].E; 78 } 79 } 80 81 // 学号不存在 82 if(curScoreA == -1) 83 { 84 if(k != m) 85 cout << "N/A" << endl; 86 else 87 cout << "N/A"; 88 89 continue; 90 } 91 92 for(int i = 1; i <= n; ++i) 93 { 94 if(stu[i].id != sid) 95 { 96 // 注意这里不能写等号,分数一样都按排名最前的来算 97 if(stu[i].A > curScoreA) 98 curRankA++; 99 if(stu[i].C > curScoreC) 100 curRankC++; 101 if(stu[i].M > curScoreM) 102 curRankM++; 103 if(stu[i].E > curScoreE) 104 curRankE++; 105 } 106 } 107 108 curRank = getMin(curRankA, curRankC, curRankM, curRankE) ; 109 if(curRank == curRankA) 110 curRankSubject = 'A'; 111 else if(curRank == curRankC) 112 curRankSubject = 'C'; 113 else if(curRank == curRankM) 114 curRankSubject = 'M'; 115 else if(curRank == curRankE) 116 curRankSubject = 'E'; 117 118 rank1[sid] = curRank; 119 rank2[sid] = curRankSubject; 120 121 122 if(k != m) 123 cout << rank1[sid] << ' ' << rank2[sid] << endl; 124 else 125 cout << rank1[sid] << ' ' << rank2[sid]; 126 127 128 } 129 130 131 return 0; 132 }