#T152. 合影效果
合影效果
Description
Xiao Yun and her friends went hiking in Xiangshan and were captivated by the beautiful scenery, wanting to take a group photo.
If they stand in a single row, with all the males on the left (from the photographer's perspective) arranged from shortest to tallest from left to right, and all the females on the right arranged from tallest to shortest from left to right, what would the final arrangement look like (assuming everyone has a unique height)?
Input Format
The first line is the number of people n (2 ≤ n ≤ 40, with at least 1 male and 1 female).
The following n lines each contain a person's gender (male or female) and height (a floating-point number in meters), separated by a space.
Output Format
n floating-point numbers, simulating the heights of each person from left to right in the photographer's view after the arrangement.
Each floating-point number should be rounded to 2 decimal places, with adjacent numbers separated by a single space.
Example Input:
5
male 1.75
female 1.68
male 1.83
female 1.72
female 1.60
Example Output:
1.75 1.83 1.72 1.68 1.60
Explanation:
- The males are sorted in ascending order: 1.75, 1.83 → [1.75, 1.83].
- The females are sorted in descending order: 1.68, 1.72, 1.60 → [1.72, 1.68, 1.60].
- The final arrangement is the concatenation of the sorted males and females: [1.75, 1.83, 1.72, 1.68, 1.60].
Note:
- All heights are unique.
- The output must strictly follow the specified format, including rounding and spacing.
Here’s the Python code to solve the problem:
n = int(input())
males = []
females = []
for _ in range(n):
gender, height = input().split()
height = float(height)
if gender == 'male':
males.append(height)
else:
females.append(height)
# Sort males in ascending order
males_sorted = sorted(males)
# Sort females in descending order
females_sorted = sorted(females, reverse=True)
# Combine the two lists
result = males_sorted + females_sorted
# Format the output to 2 decimal places and join with spaces
output = ' '.join([f"{h:.2f}" for h in result])
print(output)
Explanation of the Code:
-
Input Handling:
- Read the number of people
n. - For each person, read their gender and height, then separate them into
malesandfemaleslists.
- Read the number of people
-
Sorting:
- Sort
malesin ascending order (shortest to tallest). - Sort
femalesin descending order (tallest to shortest).
- Sort
-
Combining and Formatting:
- Concatenate the sorted
malesandfemaleslists. - Format each height to 2 decimal places and join them into a space-separated string for output.
- Concatenate the sorted
This approach efficiently solves the problem while adhering to the specified constraints and formatting requirements.
6
male 1.72
male 1.78
female 1.61
male 1.65
female 1.70
female 1.56
1.65 1.72 1.78 1.70 1.61 1.56