Diamond Hands
InterviewTime limit2sMemory limit512 MB
Given stock price differences at n known days, reconstruct a history of +1 and -1 streaks from day 1 to day d_n using the fewest streaks, or report impossibility.
- Level
Medium7 of 10
- Topics
- Greedy, Implementation, Math, Intervals
- Solved
- No attempts yet
Problem
The "Diamond Hands" corporation has a long and eventful history. Starting from its foundation, it had many successful and unsuccessful days. For simplicity, call a day successful if its stock price increased by one (in abstract units). Similarly, call a day unsuccessful if its stock price decreased by one. As often happens, successful days come in long streaks, and so do unsuccessful days. There is no middle ground: every day is either successful or unsuccessful.
You want to figure out which days were successful and which were unsuccessful for the corporation. To do this, you obtained the historical stock price data: pairs , meaning that days after the stock was issued, the difference from the starting stock price was units ( can be any integer, including negative numbers).
Represent the corporation's history with the minimum number of streaks of successful or unsuccessful days, or report that the data contains an error and it is impossible. If several answers achieve the minimum number of streaks, output any one of them.
Input
The first line contains an integer (). The next lines each contain two integers (; ; for every from to ).
Output
If the historical stock price data contains errors, output . Otherwise, print , the number of streaks, on the first line. The next lines describe the streaks of successful or unsuccessful days. Each line must contain a pair (; ), meaning that the next streak lasted days and was successful if , or unsuccessful if .
The description of the streaks must be in chronological order, starting from the day the stock was issued and ending on day . That is, the sum of all must equal .
Hint
In the first example, the first three days are successful, so after 2 days the difference is 2, and after 3 days the difference is 3. The next three days are unsuccessful, so after 5 days the difference becomes 1, and after 6 days the stock price is back to its initial value. The last seventh day is successful, so the final difference after 7 days is 1.