日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

信息学奥赛一本通 1176:谁考了第k名 | OpenJudge NOI 1.10 01:谁考了第k名

發布時間:2025/3/17 54 豆豆
生活随笔 收集整理的這篇文章主要介紹了 信息学奥赛一本通 1176:谁考了第k名 | OpenJudge NOI 1.10 01:谁考了第k名 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【題目鏈接】

ybt 1176:誰考了第k名
OpenJudge NOI 1.10 01:誰考了第k名

【題目考點】

1. 結構體 排序

【君義精講】排序算法

2. printf %g輸出

為簡潔輸出,如果輸出的數字有小于等于6位有效數字,則直接輸出,沒有小數點末尾的0。如果有效數字多于6位,則以科學計數法形式輸出。
直接cout輸出浮點型量,即為以printf("%g")形式輸出浮點型量

double a; cin >> a; cout << a << endl; printf("%g", a);//兩種輸出的效果完全一樣

【解題思路】

結構體對象排序時,比較的是對象的成員變量,交換的是對象整體。
該題為降序排序。

【題解代碼】

解法1:冒泡排序

#include<bits/stdc++.h> using namespace std; struct Stu//學生類 {int num;//學號 double score;//分數 }; int main() {int n, k;Stu stu[105];cin >> n >> k;for(int i = 1; i <= n; ++i)cin >> stu[i].num >> stu[i].score;for(int i = 1; i <= n-1; ++i)//冒泡排序 for(int j = 1; j <= n-i; ++j)if(stu[j].score < stu[j+1].score)swap(stu[j], stu[j+1]);cout << stu[k].num << ' ' << stu[k].score; return 0; }

解法2:插入排序

#include<bits/stdc++.h> using namespace std; struct Stu//學生類 {int num;//學號 double score;//分數 }; int main() {int n, k;Stu stu[105];cin >> n >> k;for(int i = 1; i <= n; ++i){cin >> stu[i].num >> stu[i].score;for(int j = i; j > 1; j--){if(stu[j].score > stu[j-1].score)swap(stu[j], stu[j-1]);elsebreak;}}cout << stu[k].num << ' ' << stu[k].score; return 0; }

解法3:使用STL sort函數

  • 使用數組,重載小于號運算符
#include<bits/stdc++.h> using namespace std; struct Stu//學生類 {int num;//學號 double score;//分數 bool operator < (const Stu &b) const{return score > b.score;} }; int main() {int n, k;Stu stu[105];cin >> n >> k;for(int i = 1; i <= n; ++i)cin >> stu[i].num >> stu[i].score;sort(stu+1, stu+1+n);cout << stu[k].num << ' ' << stu[k].score; return 0; }
  • 使用vector,寫比較函數
#include<bits/stdc++.h> using namespace std; struct Stu//學生類 {int num;//學號 double score;//分數 }; bool cmp(Stu a, Stu b) {return a.score > b.score; } int main() {int n, k;vector<Stu> stu; Stu a;cin >> n >> k;for(int i = 1; i <= n; ++i){cin >> a.num >> a.score;stu.push_back(a);}sort(stu.begin(), stu.end(), cmp);cout << stu[k-1].num << ' ' << stu[k-1].score;//vector下標從0開始 return 0; }

總結

以上是生活随笔為你收集整理的信息学奥赛一本通 1176:谁考了第k名 | OpenJudge NOI 1.10 01:谁考了第k名的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。