The objective is to arrange a group of people based on specific gender and height criteria for a photo. Males must be positioned on the left side, sorted in ascending order of height. Females must be positioned on the right side, sorted in descending order of height. All heights are distinct.
Approach 1: Categorical Separation
This method segregates the input into two distinct containers based on gender, applies the respective sorting algorithms, and then merges the results during output.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
int main() {
int count;
std::cin >> count;
std::vector<double> males, females;
for (int i = 0; i < count; ++i) {
std::string gender;
double height;
std::cin >> gender >> height;
if (gender == "male") males.push_back(height);
else females.push_back(height);
}
std::sort(males.begin(), males.end());
std::sort(females.begin(), females.end(), std::greater<double>());
std::cout << std::fixed << std::setprecision(2);
for (double h : males) std::cout << h << " ";
for (double h : females) std::cout << h << (h == females.back() ? "" : " ");
return 0;
}
Approach 2: Custom Comparator Structure
By defining a structure to hold individual data, we can utilize a custom comparator within a single std::sort call. This defines the priority: males come before females, and within the same gender, the height follows the specific ascending/descending order.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
struct Participant {
bool isMale;
double height;
};
int main() {
int n;
std::cin >> n;
std::vector<Participant> group(n);
for (int i = 0; i < n; ++i) {
std::string g;
std::cin >> g >> group[i].height;
group[i].isMale = (g == "male");
}
std::sort(group.begin(), group.end(), [](const Participant& a, const Participant& b) {
if (a.isMale != b.isMale) return a.isMale > b.isMale;
return a.isMale ? (a.height < b.height) : (a.height > b.height);
});
std::cout << std::fixed << std::setprecision(2);
for (const auto& p : group) std::cout << p.height << " ";
return 0;
}