A box ranking built from an array of pointers
There are n boxes numbered 1 to n, and box i weighs w_i.
The ranking has n slots, and each slot points to one box.
At first, slot r points to box r.
There are five commands.
- sort: rebuild the ranking.
Slots pointing to heavier boxes come first; for equal weights, the box with the smaller number comes first.
- add r v: add v to the weight of the box that slot r of the ranking points to.
The ranking is not rebuilt.
- swap i j: exchange the weights of box i and box j.
The slots of the ranking keep pointing to the same numbered boxes.
i and j may be equal, in which case nothing changes.
- who r: print on one line the number of the box that slot r of the ranking points to.
- show: print on one line the n weights of the boxes the slots point to, from the first slot on, separated by single spaces.
The first line gives n and q, the second line gives w_1 to w_n, and the next q lines give one command each.
Try keeping the weights in an array int w[n] and making the ranking an array of pointers int *rank[n] into it.
For sort, do not move the weights: arrange only the pointers with qsort (std::sort in C++).
For equal weights compare the two pointers themselves, and for who find the number by pointer subtraction rank[r - 1] - w.
Write swap as a function void swap_weight(int *a, int *b) that receives the addresses of the two slots.
- Input
- 1 ≤ n ≤ 1,000, 1 ≤ q ≤ 2,000, 1 ≤ r, i, j ≤ n.
Weights and v are integers; at the start and after everyadd, every weight is between -2,000,000,000 and 2,000,000,000 (|v| is within this range too).
Allshowcommands together print at most 15,000 numbers.whoorshowappears at least once. - Output
- One line per
whoand pershow
4 10 5 -2 5 7 sort show who 2 add 4 10 swap 1 2 show sort show who 3 swap 3 3
7 5 5 -2 1 7 8 5 5 8 7 5 5 2