這道題其實不難,以前用桶排序寫的程序很麻煩最終只獲得了80分,不知道錯在哪裏…
看題解大佬用的結構體感受很是妙
思路很簡單,定義一個學生的結構體,利用這個保存學生的學號和成績,並重載cmp方法,以便調用sort函數
這道題給個人啓發就是:當涉及到多個元素的排序時(如一個學生有學號.成績 一個商品有價格,尺碼),這時使用結構體並用sort函數進行排序是很是方便的
貼上代碼:c++
#include<bits/stdc++.h> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ typedef struct student { int num; int grade; }student; student s[10000]; //重載cmp函數,用於sort比較 int cmp(student s1,student s2){ if(s1.grade>s2.grade) { return true; } else if(s1.grade == s2.grade){ //若是分數相同則比較學號 if(s1.num<s2.num) return true; else return false; } else return false; } int n,m,line,gradeLine,sum; int main(int argc, char** argv) { cin >> n >> m; for(int i = 0;i<n;i++){ cin >> s[i].num >> s[i].grade; } //錄取排名 line = floor(m*1.5); //進行排序 sort(s,s+n,cmp); //分數線 gradeLine = s[line-1].grade; for(int i = 0;i<n;i++){ if(s[i].grade>=gradeLine) sum++; } cout << gradeLine << " " << sum << endl; for(int i = 0;i<sum;i++){ cout << s[i].num <<" " << s[i].grade << endl; } return 0; }