【題目來源】
https://www.acwing.com/problem/content/3428/
【題目描述】
N 只小白鼠,每只鼠頭上戴著一頂有顏色的帽子。
現在稱出每只白鼠的重量,要求按照白鼠重量從大到小的順序輸出它們頭上帽子的顏色。
帽子的顏色用 red,blue 等字符串來表示。
不同的小白鼠可以戴相同顏色的帽子。
白鼠的重量用整數表示。
【輸入格式】
第一行為一個整數 N,表示小白鼠的數目。
下面有 N 行,每行是一只白鼠的信息。第一個為不大于 100 的正整數,表示白鼠的重量;第二個為字符串,表示白鼠的帽子顏色,字符串長度不超過 10 個字符。
注意:白鼠的重量各不相同。
【輸出格式】
按照白鼠的重量從大到小的順序輸出白鼠的帽子顏色。
【數據范圍】
1≤N≤100
【輸入樣例】
3
30 red
50 blue
40 green
【輸出樣例】
blue
green
red
【算法分析】
一、本題的一種實現方法需要按結構體某一字段對結構體數組進行排序,詳見:
https://blog.csdn.net/hnjzsyjyj/article/details/120184972
例如,若自定義的結構體 Person 的內容如下:
struct Person {string name;int age;float height;
};
則可自定義的遞增函數 up()、遞減函數 down() 的內容如下:
int up(Person u,Person v) { //ascending by heightif(u.height==v.height) return u.name<v.name; //If equal,ascending by namereturn u.height<v.height;
}int down(Person u,Person v) { //descending by heightif(u.height==v.height) return u.name>v.name; //If equal,descending by namereturn u.height>v.height;
}
若 p 為結構體數組,則在主函數中調用遞增函數 up()、遞減函數 down() 的代碼如下:
sort(p,p+n,up); //Sort the structured array p by ascending field heightsort(p,p+n,down); //Sort the structured array p by descending field height
二、本題的另一種實現方法是利用STL pair,然后調用 sort() 函數對 STL pair 進行排序。需要注意的是,sort() 函數默認是按照 pair 的 first 域進行升序排序。如果 first 域相同,則按照 second 域進行升序排序。
若 p 為 pair 數組,則對其 first 域默認進行升序排序的代碼如下:
sort(p,p+n); //By default, ascending by the first field of array p
【算法代碼一:結構體排序】
#include <bits/stdc++.h>
using namespace std;
const int maxn=105;struct node {int w;string color;
} a[maxn];bool down(node a,node b){return a.w>b.w; //descending by weight
}int main(){int n;cin>>n;for(int i=1;i<=n;i++){cin>>a[i].w>>a[i].color;}sort(a+1,a+1+n,down);for(int i=1;i<=n;i++){cout<<a[i].color<<endl;}
}/*
in:
3
30 red
50 blue
40 greenout:
blue
green
red
*/
【算法代碼二:STL pair】
#include <bits/stdc++.h>
using namespace std;const int maxn=105;
pair<int,string> q[maxn];int main() {int n;cin>>n;for(int i=0; i<n; i++) {cin>>q[i].first>>q[i].second;}sort(q,q+n); //By default, ascending by the first fieldfor(int i=n-1; i>=0; i--) {cout<<q[i].second<<endl;}return 0;
}/*
in:
3
30 red
50 blue
40 greenout:
blue
green
red
*/
【參考文獻】
https://blog.csdn.net/hnjzsyjyj/article/details/120184972
https://blog.csdn.net/qq_27538633/article/details/126441458
?