按性别分组后将男生升序、女生降序排列并固定输出两位小数。
OJ: noi_openjudge
题目 ID: ch0110-07
难度:入门
标签:排序模拟python
日期: 2026-07-30 23:01
题意
从拍照者视角,男生全部站在左侧并按身高从矮到高排列,女生站在右侧并按身高从高到矮排列。所有身高输出两位小数。
思路
读入时按性别分到 boys 和 girls 两个列表。男生升序、女生降序后直接拼接。格式化字符串 f"{height:.2f}" 保证每个身高恰好两位小数。
代码
Python代码
python
people_count = int(input())
boys = []
girls = []
for _ in range(people_count):
gender, height = input().split()
if gender == "male":
boys.append(float(height))
else:
girls.append(float(height))
ordered_heights = sorted(boys) + sorted(girls, reverse=True)
print(" ".join(f"{height:.2f}" for height in ordered_heights))C++代码
cpp
#include <cstdio>
int n;
double boy[100];
int boy_cnt = 0;
double girl[100];
int girl_cnt = 0;
int push(double x,bool is_boy){
if(is_boy)
boy[++boy_cnt] = x;
else
girl[++girl_cnt] = x;
}
void init(){
scanf("%d",&n);
int i;
double t;
char str[100];
for (i=1;i<=n;i++){
scanf("%s",str);
scanf("%lf",&t);
push(t,str[0] == 'm');
}
}
void xchg(double &a,double &b){
double t = a; a = b; b =t;
}
void quick_sort_boy(int l,int r){
if( l >= r) return ;
double key = boy[l];
int i = l,j = r;
while( i != j ){
while( i< j && key <= boy[j])
j--;
while( i <j && key >= boy[i])
i++;
if( i < j){
xchg(boy[i],boy[j]);
}
}
boy[l] = boy[i];
boy[i] = key;
quick_sort_boy(l,i-1);
quick_sort_boy(i+1,r);
}
void quick_sort_girl(int l,int r){
if( l >= r) return ;
double key = girl[l];
int i = l,j = r;
while( i != j ){
while( i< j && key >= girl[j])
j--;
while( i <j && key <= girl[i])
i++;
if( i < j){
xchg(girl[i],girl[j]);
}
}
girl[l] = girl[i];
girl[i] = key;
quick_sort_girl(l,i-1);
quick_sort_girl(i+1,r);
}
int main(){
init();
quick_sort_boy(1,boy_cnt);
quick_sort_girl(1,girl_cnt);
int i;
for (i=1;i<=boy_cnt;i++){
printf("%.2lf ",boy[i]);
}
for (i=1;i<=girl_cnt;i++){
printf("%.2lf ",girl[i]);
}
return 0;
}复杂度
时间复杂度为
总结
分组的先后顺序是输出结构的一部分,两个组内部再各自排序即可。