Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.
Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.
The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.
Each customer is characterized by three values: t_i — the time (in minutes) when the i-th customer visits the restaurant, l_i — the lower bound of their preferred temperature range, and h_i — the upper bound of their preferred temperature range.
A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the i-th customer is satisfied if and only if the temperature is between l_i and h_i (inclusive) in the t_i-th minute.
Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
Input
Each test contains one or more test cases. The first line contains the number of test cases q (1 ≤ q ≤ 500). Description of the test cases follows.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 100, -10^9 ≤ m ≤ 10^9), where n is the number of reserved customers and m is the initial temperature of the restaurant.
Next, n lines follow. The i-th line of them contains three integers t_i, l_i, and h_i (1 ≤ t_i ≤ 10^9, -10^9 ≤ l_i ≤ h_i ≤ 10^9), where t_i is the time when the i-th customer visits, l_i is the lower bound of their preferred temperature range, and h_i is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.
The customers are given in non-decreasing order of their visit time, and the current time is 0.
Output
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
At 2-nd minute, change the state to off (the temperature is 2).
At 5-th minute, change the state to heating (the temperature is 2, the 1-st customer is satisfied).
At 6-th minute, change the state to off (the temperature is 3).
At 7-th minute, change the state to cooling (the temperature is 3, the 2-nd customer is satisfied).
At 10-th minute, the temperature will be 0, which satisfies the last customer.
In the third case, Gildong can change the state to heating at 0-th minute and leave it be. Then all customers will be satisfied. Note that the 1-st customer's visit time equals the 2-nd customer's visit time.
In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
We need to determine if it's possible to control the temperature over time (starting at time 0 with initial temperature m, AC initially off) such that at each customer's visit time t_i, the temperature lies within [l_i, h_i]. We can change state at any integer minute (including time 0?). The AC states: off (temperature constant), heating (+1 per minute), cooling (-1 per minute). We can change state arbitrarily at integer minutes. Starting state is off at time 0 (so from time 0 to 1, the state is off). Actually careful: At time 0, we are at the start, and we can change state at time 0? The problem says: "The air conditioner is off initially." "Gildong can change the state as many times as he wants, at any integer minutes." So at time 0, we can change state (maybe before any time passes). Typically, we consider that at integer moments, we can set the state for the upcoming interval. Temperature evolves as piecewise linear with slopes -1,0,1. The temperature at integer times? Since changes happen at integer minutes, and temperature changes at rate per minute, we can think of temperature as defined for all real times, but we only care at integer visit times (minutes). The temperature changes linearly between integer times. The control is piecewise constant on intervals [k, k+1) with state chosen at integer time k (and possibly at k+?). However, we can also change state at the same minute as a customer arrives? Usually, yes, we can change state at any integer minute, including the minute when a customer arrives. But since the state change is instantaneous at that minute, the temperature at that exact minute (integer) would be after any immediate change? We need to be careful about ordering: At time t_i (integer), we have a temperature. We can set the state right at that moment, but that would affect future temperature, not the instantaneous temperature at that moment. So the temperature at time t_i is determined by the history up to time t_i inclusive? Actually if state is set at integer times, and we consider temperature as continuous, the state on interval [t, t+1) is determined by the decision at time t. At the exact integer time t, the temperature is the value at the end of the previous interval? But because we can also set state at that integer time, it's ambiguous. However, typical approach in such problems (like Codeforces problem "Heating, Cooling, Off" maybe) is to treat the process as we have a current temperature, and between customer visits, we have some time interval during which we can adjust the temperature within constraints of maximum/minimum changes possible. Since we can change state arbitrarily, the temperature path can be any piecewise linear function with slope in {-1,0,1}. So essentially, given time intervals between events, we can change temperature by at most the length of time (by heating or cooling) but we can also choose not to change as much. And we can also keep temperature constant. So it's like we have a range of possible temperatures we can achieve at each customer visit, given the allowed adjustments between visits.
We can model this as: starting at time 0 with temperature m. Then for each customer in order of increasing t_i (they are sorted non-decreasing), we have an interval of time between the previous time (prev_t) and current time t_i. During that delta = t_i - prev_t minutes, we can adjust the temperature by at most delta (since maximum absolute change is delta if we heat or cool continuously). So the set of achievable temperatures at time t_i from a starting temperature x at prev_t, given we can choose any path, is the interval [x - delta, x + delta] (because we can cool or heat at max rate, but we can also stay anywhere in between). Actually careful: Since we can also keep constant, we can achieve any temperature in that interval? Yes, because we can decide to heat for a minutes, then cool for b minutes, etc. But is any real number achievable? Since changes are discrete 1 per minute, and we are at integer times? The times are integer, the temperature is integer? The temperature changes by 1 per minute, and initial temperature is integer, so after integer minutes, the temperature will be integer. So the set of reachable integer temperatures at integer time t_i from integer starting temperature x at integer time prev_t is all integers between x - delta and x + delta inclusive, because we can go +1 each minute (heating) for some minutes and 0 for others? Actually to achieve a specific integer y within that range, we need to have net change = y - x. Since each minute we can choose to change by -1,0,+1, the net change after delta steps can be any integer between -delta and +delta, but only with parity? Let's check: Starting at integer, each minute we add -1,0, or +1. After delta minutes, the sum of these choices is the net change. The set of possible sums is all integers between -delta and +delta that have the same parity as delta? Not necessarily. For example, delta=1: we can get -1,0,1 (all). For delta=2: choices: two numbers each in {-1,0,1}. The sum can be -2, -1, 0, 1, 2. Let's see if -2: two -1 => sum -2. -1: -1+0 => -1. 0: 0+0 or -1+1 => 0. 1: 1+0 => 1. 2: 1+1 => 2. So all integers in between. For delta=3: sums from -3 to 3, possible: -3: -1-1-1, -2: -1-1+0, -1: -1+0+0, 0: 0+0+0 or -1+1+0, 1: 1+0+0, 2: 1+1+0, 3: 1+1+1. So all integers in range. In general, by adding steps of +1 and -1 we can achieve any integer with parity same as delta? Actually if we use only +1 and -1, the sum's parity equals (number of +1) - (number of -1). But +1 and -1 each change parity? The parity of sum is (number of +1 mod 2) - (number of -1 mod 2) mod 2? Actually sum mod 2 = ( (#+1) - (#-1) ) mod 2 = (#+1 + #-1) mod 2 = total number of non-zero steps mod 2? Because -1 ≡ +1 mod 2? Since -1 mod 2 = 1 mod 2? Wait -1 ≡ 1 (mod 2) because modulo 2, -1 ≡ 1. So adding -1 is same as adding 1 mod 2. So each step that is either +1 or -1 changes the temperature by an odd amount? Actually +1 changes parity; -1 also changes parity (since -1 is odd). So any minute where we choose heating or cooling toggles parity; minute where we choose off does not change parity. So after delta minutes, parity of temperature = initial parity + (number of heating+cooling minutes) mod 2. Since we can choose any number of such minutes between 0 and delta, the parity of final temperature can be either same as initial parity (if we use even number of toggling minutes) or opposite (if odd). Therefore we can achieve any integer within the range because we can adjust parity by optionally using an off step. For any y in [x-delta, x+delta], difference d = y-x, absolute value ≤ delta. We need to achieve net change d. This is possible by using d' = d (if d ≥ 0) heating minutes, and off for the rest? But if d is positive, we can use d heating minutes and delta-d off minutes; net change = d. That yields parity change: heating minutes toggle parity; if d is odd, parity flips; if d even, parity stays. Since we have off minutes, that's fine. So any integer d with |d| ≤ delta is achievable by using exactly |d| steps of appropriate direction and the rest off. So yes, any integer between x-delta and x+delta inclusive is achievable.
Thus the reachable set is the integer interval.
Therefore, we can treat this as we maintain an interval of possible temperatures that we can have at the current time, given constraints from previous customers. Initially at time 0, we have exactly temperature m (so possible set = [m, m]). Then for each customer in order, we have time elapsed since previous event. Let delta_t = t_i - prev_t. Before considering the customer's constraints, we can adjust: from any temperature in the previous feasible interval, after delta_t minutes we can achieve any temperature in the expanded interval: [prev_low - delta_t, prev_high + delta_t] but we also need to intersect with the feasible set of temperatures that were possible from previous step? Actually previous feasible set is some interval [L_prev, R_prev] (all integer temperatures that could be at time prev_t). After delta_t minutes, the set of possible temperatures at time t_i (before considering the customer's constraints) is:
[L_prev - delta_t, R_prev + delta_t] (since from the lowest possible previous temperature we can go down by at most delta_t, and from the highest possible we can go up by at most delta_t; and everything in between can be reached from some previous temperature because we have ability to adjust). Actually we need to ensure that the entire interval is reachable: For any temperature y in [L_prev - delta_t, R_prev + delta_t], can we find a previous temperature x in [L_prev, R_prev] such that |y-x| ≤ delta_t? Yes: If y ≤ R_prev and y ≥ L_prev, we can take x = y and use zero change. If y > R_prev, we can take x = R_prev and heat for (y - R_prev) minutes, which is ≤ delta_t if y - R_prev ≤ delta_t. Since y ≤ R_prev + delta_t, condition holds. Similarly if y < L_prev, we can cool from L_prev. So indeed the reachable set is exactly that interval. So we can compute feasible range before constraint: [low_possible, high_possible] = [L_prev - delta_t, R_prev + delta_t].
Then we need to satisfy the customer: temperature must be within [l_i, h_i] at time t_i. So the new feasible interval after the customer is the intersection: [max(low_possible, l_i), min(high_possible, h_i)]. If this interval is empty (i.e., low > high), then impossible.
After processing all customers, answer is YES.
But careful: The customers are given in non-decreasing order of t_i, but there could be multiple customers at the same time. In that case, delta_t = 0 for subsequent same-time customers. We need to process them sequentially. For same time, after handling first customer, we have a feasible interval (intersection). Then for the next customer at same time, we have delta_t=0, so reachable set is exactly the interval from previous step (since no time passes). Then we intersect with that customer's range. So effectively, for all customers at same time, we need the intersection of all their ranges and also must be reachable from previous step with zero time, meaning that the previous feasible interval must have non-empty intersection with the intersection of all ranges for that time. That is equivalent to intersect them one by one.
So algorithm per test case:
n, m.
prev_t = 0.
low = m, high = m.
for each customer (t_i, l_i, h_i) in order:
delta = t_i - prev_t.
low = low - delta
high = high + delta
// Now low and high represent reachable range at time t_i before considering constraints.
// Intersect with customer's range:
low = max(low, l_i)
high = min(high, h_i)
if low > high: return NO
prev_t = t_i
After loop: YES.
Note: m can be negative large. But we are using integers, Python can handle.
But is there any nuance? For example, the AC can be changed at any integer minute, but does it need to be in a specific state at the start? Initially off. That's fine because we can decide to change at time 0 to heating or cooling, and then proceed. So our modeling is correct.
Edge Cases: The times can be huge up to 1e9, delta may be large, but we are just doing addition/subtraction, no loops, so fine.
But wait: The problem statement says: "The air conditioner is off initially." In our modeling, we assume we can change state at time 0 before any time passes. That means from time 0 to 1, we can be heating/cooling/off. So it's fine.
Time 0 is initial moment, no customer at time 0. So our approach is valid.
Check if there is any nuance about the fact that we can change state only at integer minutes. Could we achieve any integer temperature at integer times? Yes, as argued.
One more nuance: What about the initial state being off? That doesn't restrict us because we can change it at time 0.
Thus the solution is O(n) per test case.
Now we need to implement reading q test cases, each with n and m, then n lines.
Constraints: n up to 100, q up to 500, so total customers up to 50000, trivial.
Potential pitfalls: integer overflow? In Python, not a problem. In C++ need 64-bit.
Also note that t_i up to 1e9, delta may exceed 2e9, but with bounds on m and ranges, the low/high could become out of typical 32-bit range, so use 64-bit.
Edge case: multiple customers with same t_i: as we argued, it's fine.
One more nuance: The ordering is non-decreasing, but not necessarily strictly increasing. Our algorithm works because delta = 0 for same times, and we intersect sequentially. But careful: For same time, after processing first customer, low and high become the intersection of previous reachable range (with delta=0) and that customer's range. Then for next customer, we apply delta=0 again, so we essentially intersect further with next customer's range. That's correct. However, is there any possibility that we could have different behavior by altering state within the same minute to satisfy multiple customers? Since customers at same time arrive at the same minute, the temperature must be the same for all of them (since they visit at same instant). So the temperature must lie in intersection of all their ranges. So sequential intersection is correct.
Thus answer.
Let's code.
But wait, I recall a similar Codeforces problem: "1360E - Polygon" no, maybe "1462A" etc. But I think this is correct.
Nevertheless, double-check: Could there be a scenario where we need to consider that we can change state at any integer minute, but temperature at time t_i (which is integer) might be affected by the state we set at time t_i? For example, if we set state to heating at time t_i, does the temperature increase immediately? Typically, if we model as we can change at integer times, and the temperature evolves constantly, the state on interval [t, t+1) is determined by the decision at time t. So the temperature at integer time t is the value just before any change? Actually, we can decide at time t to change the state for the upcoming interval (t to t+1). The temperature at time t is the result of the previous interval. So we cannot affect the temperature at time t by a state change at time t. But we can also change state at exactly time t before the customer arrives? If the customer arrives at time t, they come at that moment, perhaps we can adjust the temperature at that instant by changing state at exactly that moment? The problem statement: "Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially. Each customer... visits the restaurant at time t_i. A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant." It doesn't specify if state changes happen instantly or take effect immediately. Typically in such problems, a state change at time t only affects the future after t, not the exact instant t. So our modeling that the temperature at integer times is determined solely by the state choices on previous intervals is correct.
But could we change state at time 0 before time passes? At time 0, the initial state is off. The temperature at time 0 is given as m. If we change state at time 0, what happens to temperature at time 0? The temperature is still m. So it's fine.
Thus algorithm stands.
Implementation:
def solve():
import sys
data = sys.stdin.read().strip().split()
it = iter(data)
q = int(next(it))
out = []
for _ in range(q):
n = int(next(it))
m = int(next(it))
low = m
high = m
prev_t = 0
possible = True
for i in range(n):
t = int(next(it)); l = int(next(it)); h = int(next(it))
delta = t - prev_t
low -= delta
high += delta
# intersect with [l, h]
if low < l:
low = l
elif low > h:
possible = False
# but we still need to consume remaining inputs? We can break but need to read all lines. Simpler: set flag and continue reading but ignore. Since we still need to iterate to consume input, we can just continue but not update.
# For safety, we can set low, high to something but we will break after loop? But we still need to read rest of lines. So we can set low/high but they won't matter. But we need to note that intersection fails. We'll set possible=False and later after loop print NO.
# However, we need to still update low/high? Not needed. But we must continue to read rest of inputs for this test case. So we'll just store the failure and continue the loop without further updates. But careful: if we don't update low/high, later iterations might produce wrong delta calculations? Actually if we have a failure, we don't care about later calculations because answer will be NO regardless. So we can just break? But we must still consume the remaining lines of this test case. If we break prematurely, we skip reading them and the iterator will be off. So better to read all lines anyway. We can set a flag and continue, but not perform intersection logic. But we still need to update prev_t? Not necessary because we are just reading data; we don't need to maintain state. So we can do: if not possible: just read remaining tokens? Actually we already are reading tokens sequentially; we have already read t,l,h for this customer. So to consume the remaining customers, we need to loop through remaining i. But we can just continue the loop and do nothing (i.e., no updates). However, we still need to read t,l,h for each iteration. That's done anyway. So we can structure as:
code
# after computing low/high, do:
if low > high: possible=False and maybe set low, high to some values? Actually we need to check intersection properly:
low = max(low, l)
high = min(high, h)
if low > high: possible = False; break? But we still need to read remaining lines; break would skip them. So instead of break, we can set a flag and after the loop we will check. But we still need to iterate through remaining customers to consume their tokens. So we can't break. We could store a flag and continue, but not update low/high. However, low/high will be used for next iteration. If we don't update, the low/high may be stale and cause further failures maybe incorrectly flag as impossible but we already know impossible. But we could set low/high to something that ensures later intersection always fails? Not needed; we can just continue but also need to ensure that we don't accidentally treat as possible later. We can set low=1, high=0 (empty) for subsequent steps, then any intersection will be empty, and we keep flag False. That is safe. So after detection, we can set low=1, high=0 (empty) and continue; subsequent steps will compute low -= delta etc. but then intersection will always yield low>high? Actually if low=1, high=0, after subtracting delta, low = 1 - delta, high = 0 + delta. For positive delta, low becomes less, high becomes positive, they might cross? But we will then intersect with customer range and likely get non-empty? But that would incorrectly revert possible? Actually we need to ensure that after a failure, we maintain that the state is impossible. So we should keep low>high always. So we can set low = 1, high = 0 (so low>high). Then when we compute low -= delta, high += delta, low becomes 1-delta, high becomes delta. For large delta, low may become negative large, high positive, but low could be <= high depending on delta. For example, delta=10 gives low=-9, high=10 => low <= high. That would make the interval non-empty. Then intersecting with some range could produce a non-empty interval, and we might incorrectly think it's possible if we later check? But we still have flag false, we will ignore. However if we only check at the end flag, it's fine if we keep flag false. But if we want to avoid extraneous computations, we can simply break and then skip reading remaining input by reading tokens into a dummy variable? But easier: we can read all tokens upfront, which we are doing via splitting. So we are not reading line by line; we have all tokens in a list. So we can break and then skip the rest of the customers by advancing the loop index? But we are iterating over range(n) and we have already read t,l,h for each iteration. If we break, we won't read the remaining lines, but we have already retrieved all tokens from the iterator because we call next(it) inside loop. If we break early, we haven't yet called next(it) for the remaining customers; then later tokens will be read for the next test case incorrectly. So we must consume the tokens for the remaining customers. So we cannot break without consuming.
Option 1: Not break, but after detection, set a flag and then for subsequent iterations, we still need to read t,l,h (which we will) but we should skip the logic. To ensure we don't inadvertently affect flag, we can just not update low/high and continue. But low/high are still defined; if we leave them as previous (maybe valid range), then subsequent steps might compute new low/high that accidentally become non-empty, but we don't care because flag is already false and we will output NO. So it's fine. The only risk is that we might have an error if we try to intersect after failure and low/high become valid and we overwrite flag to True? No, we won't change flag back. So it's safe.
But we could also set low = 1, high = 0 after failure to keep low>high. However, that would require computing low/high adjustments for delta, which might flip them to non-empty and then intersect could produce non-empty, but we still keep flag false. So either way is fine.
Simpler: Keep a boolean possible = True. Inside loop, if possible:
compute delta, update low/high, intersect.
if low>high: possible=False
Else:
# just read t,l,h but do nothing (skip). But we already read them before condition? Actually we read t,l,h at start of each iteration regardless. So we can do:
for i in range(n):
t = int(next(it)); l = int(next(it)); h = int(next(it))
if not possible:
continue
delta = t - prev_t
low -= delta
high += delta
# intersect
low = max(low, l)
high = min(high, h)
if low > high:
possible = False
else:
prev_t = t # Only update if success? Actually if we fail, we still might want to update prev_t? Not necessary because we won't use it further as we will skip. But if we skip later, we don't need prev_t. So we can update only when possible.
But note: prev_t must be updated only when we succeed, because for next customer we need correct previous time. So if possible is True, we update prev_t = t. If possible becomes false, we skip updates and continue skipping remaining customers.
Thus implementation is straightforward.
But need to be careful: In case possible is False, we skip the logic but we have already consumed t,l,h. That's fine. We also skip updating prev_t, but that doesn't matter because we skip all subsequent logic. So no issue.
Edge Cases: Time differences large, low/high might go out of integer bounds but Python fine.
Now output "YES" if possible else "NO".
Let's test with sample.
Also consider case where t_i could be zero? According to constraints, t_i >= 1, so no customer at time 0.
Ok.
But wait: There's a subtlety: The AC initially off. That means from time 0 to 1, the AC is off unless we change state at time 0. In our model, we allowed to change at time 0. So that is fine.
One more nuance: Could the AC be turned on and off multiple times within a minute? No, only at integer minutes. So we can't change continuously.
Thus modeling is correct.
I'll write final solution.
Now let's think about proving correctness formally.
The idea: maintain interval [L, R] of temperatures that are achievable at time prev_t given constraints of previous customers. Initially [m,m]. For next customer at time t, with delta = t - prev_t, any achievable temperature at t must be within [L - delta, R + delta] (reachable range). Also must satisfy [l_i, h_i]. So new feasible set is intersection. If empty => impossible. If non-empty => we can pick any temperature in that intersection and there exists a control achieving it while respecting previous constraints. By induction, after all customers, if non-empty, possible.
We need to show that if the intersection is non-empty, there exists a control sequence that meets all customers up to i. This is typical: we can choose a temperature x_i in the intersection at time t_i. By backward construction, we can find a path from the previous feasible temperature x_{i-1} to x_i within delta time because |x_i - x_{i-1}| ≤ delta? Actually we need to ensure that from the previous feasible set, we can achieve x_i. Since we only know that x_i ∈ [L - delta, R + delta] where L,R are the bounds of feasible set at prev_t. However, the feasible set at prev_t is the interval [L,R] (all temperatures that are achievable and satisfy all previous constraints). But to guarantee existence of a specific x_{i-1} such that we can go to x_i, we need to show there exists some y ∈ [L,R] with |x_i - y| ≤ delta. Because x_i could be at the extremes: if x_i = L - delta, then we need y = L, which is in [L,R]. If x_i = R + delta, need y = R. For any x_i in between, we can take y = clamp(x_i, L, R). For example, if x_i is between L and R, we can set y = x_i and change 0. If x_i > R, we can take y = R and heat for x_i - R ≤ delta because x_i ≤ R+delta. Similarly if x_i < L, cool from L. So indeed there exists a previous feasible temperature. And we can then construct control from that previous state to achieve x_i in exactly delta minutes by heating/cooling appropriately and staying off for remainder. And by induction we can construct full sequence.
Thus algorithm correct.
Now implement.
I'll code in Python.
Potential pitfalls: large input, use sys.stdin.buffer.
Will read all ints.
Testing with sample.
Write solve() function.
Now final answer.
Let's produce final code. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
it = iter(data)
q = int(next(it))
out_lines = []
for _ in range(q):
n = int(next(it))
m = int(next(it))
low = m # lower bound of achievable temperature
high = m # upper bound
prev_t = 0
possible = True
for _ in range(n):
t = int(next(it))
l = int(next(it))
h = int(next(it))
if not possible:
continue # just consume input, no further processing
delta = t - prev_t
low -= delta
high += delta
# intersect with customer's range
if low < l:
low = l
if high > h:
high = h
if low > high: # empty intersection
possible = False
else:
prev_t = t
out_lines.append("YES" if possible else "NO")
sys.stdout.write("\n".join(out_lines))