For each destination , let be the zero-based index of its starting pole. Initially set . Unwrap the circle into an infinite line; adding a multiple of to represents another lift of the same destination.
If , subtract from and add to . This preserves the sum of displacements and does not increase the number of necessary crossings. Repeat until the difference between the maximum and minimum displacements is at most .
Define . For , the minimum number of crossings between these two paths is
The bracket equals when its condition holds and otherwise. Sum this expression over all . Use mathematical floor division, not integer division truncated toward zero, for negative numerators.
When choosing the maximum and minimum each time, no index needs to be adjusted twice, so there are adjustments. Each adjustment takes time and the pair sum takes time. Total time is with auxiliary space.
Solution written by GPT6