PAT A1055 The World's Richest
PAT A1055 The World‘s Richest题目描述: Forbes magazine publishes every year its list of billionaires based on the annual ranking of the world‘s wealthiest people. Now you are supposed to simulate this job,but concentrate only on the people in a certain range of ages. That is,given the net worths of N people,you must find the M richest people in a given range of their ages. 参考代码:1 /************************************************** 2 PAT A1055 The World‘s Richest 3 **************************************************/ 4 #include <iostream> 5 #include <algorithm> 6 #include <vector> 7 8 using namespace std; 9 10 struct peopleInfo { 11 string name; 12 int age = 0; 13 int wealth = 0; 14 }; 15 16 //自定义比较函数 17 bool cmp(peopleInfo a,peopleInfo b) { 18 if (a.wealth == b.wealth) { 19 if (a.age == b.age) { 20 return a.name < b.name; 21 } return a.age < b.age; 22 } else return a.wealth > b.wealth; 23 } 24 25 int main() { 26 //读入信息 27 vector<peopleInfo> PeopleList; 28 int peopleCnt = 0,queryCnt = 0; 29 30 cin >> peopleCnt >> queryCnt; 31 32 peopleInfo temp; 33 for (int i = 0; i < peopleCnt; ++i) { 34 cin >> temp.name >> temp.age >> temp.wealth; 35 PeopleList.push_back(temp); 36 } 37 38 //对录入信息进行排序 39 sort(PeopleList.begin(),PeopleList.end(),cmp); 40 41 //按要求输出结果 42 for (int i = 0; i < queryCnt; ++i) { 43 if (i != 0) cout << endl; //避免多余换行 44 cout << "Case #" << i + 1 << ‘:‘ << endl; //注意这个:号 45 46 int maxPrint = 0,minAge = 0,maxAge = 0,printCnt = 0; 47 48 cin >> maxPrint >> minAge >> maxAge; 49 50 for (int j = 0; j < peopleCnt && printCnt < maxPrint; ++j) { //注意添加printCnt < maxPrint的限制,否则在输入信息很多的情况下会超时 51 if (PeopleList[j].age >= minAge && PeopleList[j].age <= maxAge) { 52 if (printCnt != 0) cout << endl; //避免多余换行,输出个数未知 53 54 cout << PeopleList[j].name << ‘ ‘ << PeopleList[j].age << ‘ ‘ << PeopleList[j].wealth; 55 printCnt++; 56 } 57 } 58 59 if (printCnt == 0) cout << "None"; //没有符合条件的输出时输出None 60 } 61 62 return 0; 63 } 注意事项:1:这道题花费的时间挺久的,每次都是答案错误和多种错误,而且最近感冒脑子不是很清楚,到最后才发现自己少了44行中的‘:‘符号,希望各位也能在写代码的时候看清要求避免不必要的时间浪费。 2:身体是革命的本钱,多注意自己的身体。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |