According to the condition of the problem, it is clear that it is necessary to apply stable (stable) sorting, therefore, instead of sort, stable_sort should be used.
1000 ms 256 Mb Rules for program design and list of errors in automatic problem checking