L Boarding Queue
For each \(i\) (\(1 \le i \le p\)), consider what the state of the boarding queue would be by the time you occupy traveler \(i\)’s initial location. There would have been \(p - i\) boarding steps. Travelers \(1\) to \(p - i\) would have left the boarding queue, while traveler \(x\) (for \(x \gt p - i\)) would occupy traveler \((x - (p - i))\)’s initial location.
Therefore, we can simply solve this problem by iterating \(i\) from \(1\) to \(p\). Consider all the travelers \(j\) who are initially adjacent to traveler \(i\). If \(j + (p - i) \le N\), then traveler \(j + (p - i)\) will be adjacent to you after \(p - i\) boarding steps. Insert \(j + (p - i)\) to a data structure.
After all \(p\) iterations, print the number of distinct integers in the data structure. With a data structure that supports constant-time insertion, this solution runs in \(O(r \times c + n)\) time.