P16624 [GKS 2017 #D] Sightseeing

Description

When you travel, you like to spend time sightseeing in as many cities as possible, but sometimes you might not be able to because you need to catch the bus to the next city. To maximize your travel enjoyment, you decide to write a program to optimize your schedule. You begin at city $1$ at time $0$ and plan to travel to cities $2$ to $N$ in ascending order, visiting every city. There is a bus service from every city i to the next city i + $1$. The i-th bus service runs on a schedule that is specified by $3$ integers: $S_i$, $F_i$ and $D_i$, the start time, frequency and ride duration. Formally, this means that there is a bus leaving from city i at all times $S_i + xF_i$, where x is an integer and $x \ge 0$, and the bus takes $D_i$ time to reach city i + $1$. At each city between $1$ and $N - 1$, inclusive, you can decide to spend $T_s$ time sightseeing before waiting for the next bus, or you can immediately wait for the next bus. You cannot go sightseeing multiple times in the same city. You may assume that boarding and leaving buses takes no time. You must arrive at city $N$ by time $T_f$ at the latest. (Note that you cannot go sightseeing in city $N$, even if you arrive early. There's nothing to see there!) What is the maximum number of cities you can go sightseeing in?

Input Format

The input starts with one line containing one integer $T$, which is the number of test cases. $T$ test cases follow. Each test case begins with a line containing $3$ integers, $N$, $T_s$ and $T_f$, representing the number of cities, the time taken for sightseeing in any city, and the latest time you can arrive in city $N$. This is followed by $N - 1$ lines. On the i-th line, there are $3$ integers, $S_i$, $F_i$ and $D_i$, indicating the start time, frequency, and duration of buses travelling from city i to city i + $1$.

Output Format

For each test case, output one line containing Case #x: y, where $x$ is the test case number (starting from $1$) and $y$ is the maximum number of cities you can go sightseeing in such that you can still arrive at city $N$ by time $T_f$ at the latest. If it is impossible to arrive at city $N$ by time $T_f$, output Case #x: IMPOSSIBLE.

Explanation/Hint

In the first test case, you can go sightseeing in city $1$, catching the bus leaving at time $3$ and arriving at time $4$. You can go sightseeing in city $2$, leaving on the bus at time $8$. When you arrive in city $3$ at time $10$ you immediately board the next bus and arrive in city $4$ just in time at time $12$. ### Limits $1 \le T \le 100$. **Small dataset (Test set $1$ - Visible)** $2 \le N \le 16$. $1 \le S_i \le 5000$. $1 \le F_i \le 5000$. $1 \le D_i \le 5000$. $1 \le T_s \le 5000$. $1 \le T_f \le 5000$. **Large dataset (Test set $2$ - Hidden)** $2 \le N \le 2000$. $1 \le S_i \le 10^9$. $1 \le F_i \le 10^9$. $1 \le D_i \le 10^9$. $1 \le T_s \le 10^9$. $1 \le T_f \le 10^9$.