Spider Walk
Time limit6sMemory limit1024 MB
Given n strands and m bridges in a spider web, find for each start strand the fewest bridges to add so Charlotte's autopilot walk ends at strand s.
- Level
Medium7 of 10
- Topics
- Sorting, Graph, Simulation, Greedy
- Solved
- No attempts yet
Problem
Charlotte the spider sits at the center of her spiderweb. The web consists of silken straight strands that go from the center to the outer boundary. Charlotte's web also has bridges, each connecting two adjacent strands. The two endpoints of a bridge are always the same distance from the center.
When Charlotte finishes a late-night feast at the center and wants to retreat to a corner, she walks to the edge on autopilot. She picks a starting strand and walks along it until she meets the first bridge on that strand. She crosses the bridge onto the other strand and keeps walking outward until she meets another bridge. She crosses that bridge too and repeats the process. When no bridges remain on the current strand, she walks to the end of it. Charlotte must cross all the bridges she meets. The figure shows one path Charlotte could take.

Figure I.1: The path starting from strand 4.
Charlotte's favorite corner to sleep in during the daytime is at the end of strand . For each possible starting strand, she wants to know the minimum number of bridges to add to the original web so that she ends at . Charlotte can add a bridge at any point along a strand, as long as the added bridge does not touch any other bridge. The two endpoints of an added bridge must be the same distance from the center, and the bridge must connect two adjacent strands.
Input
The first line has three integers , , and , where is the number of strands, is the number of bridges, and is Charlotte's favorite strand. Strands are labeled from 1 to in counterclockwise order. Each of the remaining lines contains two integers and describing a bridge, where is the bridge's distance from the center and is the first strand of the bridge in counterclockwise order. If , the bridge connects strands and . If , the bridge connects strands and . All bridge distances are distinct.
Output
Output lines. The -th line is the minimum number of bridges Charlotte needs to add so that she ends at strand after walking on autopilot from strand .