Iterate over each frequency. Suppose now we are on frequency i. Put all stations with frequency i in the left vector and all radio stations with frequency [i−k,i+k] into the right vector.
Now we want to calculate the number of pairs such that the left radio station is from the left vector and the right station is from right vector.
Sort the left vector by position and sort the right vector by the left bound of the stations’ range. Iterator the stations in the left vector and put all the stations in the right vector which can reach the current station in the axis(actually we need to put them in some data structure). Now we need to know how many stations in the axis can be reached by the current station. This can be done with some range-sum-query data structure(like fenwick tree): we add one on the position for each new station and use range query to find the stations we want. However, since the positions are up to 109 we also need to compress the coordinate, which is really annoying, so a simpler way to do this is to use a balanced BST in pb_ds library to find the order directly.
The lesson learnt is that when we want to find the order, especially with coordinate compression, consider pb_ds.