Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

TryOmar's blog

By TryOmar, history, 10 months ago, In English

Let's say you have a set of integers called nums, and you want to sort them based on certain criteria, such as frequency and value. Here's a brief code snippet demonstrating how you can achieve this:

const int N = 1e5 + 1;
int fr[N] = {};

// Define a custom sorting criterion
struct sortCri {
    bool operator()(int a, int b) const {
        // Customize the sorting order here
        if (fr[a] == fr[b]) return a > b;  // Sort values in descending order
        else return fr[a] < fr[b];         // Sort frequencies in ascending order
    }
};

// Create a set using the custom sorting criterion
set<int, sortCri> nums;

In the code above, we have a set called nums that will sort elements based on the criteria defined in the sortCri struct. In this example, we sort in ascending order of frequency (fr[a]) and in descending order of values (a).

You can easily adapt this code to your specific sorting requirements by modifying the conditions inside the operator() function within the sortCri struct.

  • Vote: I like it
  • +16
  • Vote: I do not like it

»
10 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Thanks for sharing these information!

»
10 months ago, # |
Rev. 5   Vote: I like it +3 Vote: I do not like it

Use lambda to make the code shorter:

set<int, decltype([](int a, int b) { return fr[a] == fr[b] ? a > b : fr[a] < fr[b]; })> nums;

I like lambda :)