e788 - b3.畢業典禮(Ceremony)
題目描述
題目要求根據學生學號和姓名,按照學院代碼、學號開頭(學士、碩士、博士)和報名順序,輸出學生上台的順序表。
解題思路
首先,定義一個結構體 inf 來儲存學生的學號、姓名和報名順序。然後,讀取輸入的學生資料,並將其儲存在 inf 結構體的陣列中。接著,使用 sort 函數對陣列進行排序,排序的比較函數 cmp 根據題目規定的順序進行比較:學院代碼、學號開頭、報名順序。最後,按照排序後的順序輸出學生的學院代碼和姓名。
複雜度分析
- 時間複雜度: O(n log n) (主要來自排序操作)
- 空間複雜度: O(n) (主要來自儲存學生資料的陣列)
程式碼
#include <iostream>
#include <algorithm>
using namespace std;
struct inf{
string id;
string name;
int time;
};
bool cmp(inf x,inf y){
if(x.id[8]>y.id[8])
return 0;
if(x.id[8]<y.id[8])
return 1;
if(x.id[0]>y.id[0])
return 0;
if(x.id[0]<y.id[0])
return 1;
if(x.time>y.time)
return 0;
return 1;
}
int main(){
int n;
cin >> n;
inf a[n];
for(int i=0;i<n;++i){
cin >> a[i].id >> a[i].name;
a[i].time=i;
}
sort(a,a+n,cmp);
for(int i=0;i<n;++i)
cout << a[i].id[8] << ": " << a[i].name << "\n";
}