题目描述
N只小白鼠(1 <= N <= 100),每只鼠头上戴着一顶有颜色的帽子。现在称出每只白鼠的重量,要求按照白鼠重量从大到小的顺序输出它们头上帽子的颜色。帽子的颜色用“red”,“blue”等字符串来表示。不同的小白鼠可以戴相同颜色的帽子。白鼠的重量用整数表示。
输入描述:
多案例输入,每个案例的输入第一行为一个整数N,表示小白鼠的数目。
下面有N行,每行是一只白鼠的信息。第一个为不大于100的正整数,表示白鼠的重量,;第二个为字符串,表示白鼠的帽子颜色,字符串长度不超过10个字符。
注意:白鼠的重量各不相同。
输出描述:
每个案例按照白鼠的重量从大到小的顺序输出白鼠的帽子颜色。
示例1
输入
3
30 red
50 blue
40 green
输出
blue
green
red
题目解析:与成绩排序差不多,定义小白鼠信息的结构体,然后根据体重进行排序,再输出颜色信息就好了。 因为是降序,所以sort中写一个bool的排序方法,按降序。 另一种不用定义结构体,使用vector也可以,但是map不用,因为map不能使用sort排序复杂。
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<map>
#include<set>
#include<vector>
using namespace std;
typedef struct{
int weight;
string color;
}mouse;
bool cmp(mouse ma,mouse mb){
return ma.weight > mb.weight;
}
int main()
{
int count,weight;
string color;
mouse mouse[100];
while(cin >> count){
for(int i = 0; i < count ; i++){
cin >> weight >> color;
mouse[i].weight = weight;
mouse[i].color = color;
}
sort( mouse , mouse + count , cmp);
for(int i = 0; i < count ; i++){
cout << mouse[i].color <<endl;
}
}
return 0;
}
/* 不用定义结构体,使用vector
bool cmp2(pair<int,string> p1,pair<int,string> p2){
return p1.first > p2.first; //pair取第一个数使用first,第二个使用 second
}
int main()
{
int count,weight;
string color;
vector<pair<int,string>> vc; //pair是stl库中定义的一种方法,将两种元素综合为一种
while(cin >> count){
for(int i = 0; i < count ; i++){
cin >> weight >> color;
vc.push_back(make_pair(weight,color));
}
sort(vc.begin(),vc.end(),cmp2);
for(int i = 0 ; i < vc.size() ; i++){
cout << vc[i].second << endl;
}
}
return 0;
}
*/