We need to compute the expected amount of money when reaching or passing goal. The board: squares 0..Y (Y>=1), with 0 start, Y goal. There are Z event squares at positions Ni (1..Y-1, distinct). Each event has type Ei, value Ai.
Roulette: X equal probability outcomes, each a number Vi (1..10). At each turn, you spin the roulette and move the piece forward by the number shown (Vi). If you land on or pass the goal (Y), the game ends. If you land on an event square (including the square after moving exactly?), the event is triggered. According to description: "Depending on the square, there are event squares where you can earn money or change the position of the pieces by stopping or passing there." Wait: "stopping or passing there." Actually: "There are event squares where you can earn money or change the position of the pieces by stopping or passing there." It might mean that if you stop on it or pass over it? But typical board game: you land on a square, you get its effect. However they say "by stopping or passing there". The phrase is ambiguous. Let's read the problem statement carefully: "The board has squares numbered 0, 1, ..., Y, and they are connected in order. There are Z special squares called event squares in the squares, and when they reach them, they perform special actions. The number of the square of the event square is given by Ni. ... Ignore the events in the squares that are advanced by the event." So this says: when they reach them (the event squares), they perform special actions. It doesn't mention passing. The phrase "stopping or passing" appears in the description of event squares: "There are event squares where you can earn money or change the position of the pieces by stopping or passing there." But the formal specification: "when they reach them, they perform special actions." So I think only landing exactly on an event square triggers the event. The phrase "passing" might be a misinterpretation; maybe they meant "stopping or passing" in the sense of "when you stop on them or pass over them"? Let's check the example provided: In the example, they had a game with Y=2, one event square at 1, type 2 (get 100). Roulette: X=2? Actually the example diagram: It shows three squares: start (0), event (1), goal (2). Roulette values: 1 or 2. They described: First spin, if 1, you reach event square and money becomes 100; if 2, you reach goal and money remains 0. Then if you reached event, you spin second time and no matter what (1 or 2) you reach goal because from square 1, moving 1 goes to 2, moving 2 goes to 3 (exceeds goal). So both lead to goal, with money 100. So that matches only triggering event when landing exactly on square 1. So passing over (if moving from 0 by 2 you pass over square 1 but don't stop, they didn't get event). So event triggers only when you land exactly on that square.
Now event types:
1: Advance by specified value Ai (1-10). So you move forward Ai squares. That's like a jump. After this jump, does it check for events? The problem says: "Ignore the events in the squares that are advanced by the event." So if you advance by Ai, you move forward, passing intermediate squares, and you do not trigger events on those squares. Also if you land exactly on an event square after the jump? They said "Ignore the events in the squares that are advanced by the event." But what about the square you land on after advancing? Usually "advanced by the event" refers to the movement caused by the event. But do you trigger events at the destination? The phrase "ignore the events in the squares that are advanced by the event" might mean that during that advance, you don't trigger events on squares you pass or land? The wording: "Ignore the events in the squares that are advanced by the event." Could be interpreted: When you execute a type 1 event, you move forward Ai squares. During this movement, any event squares you pass (including the landing square if it's an event) are ignored. However, is the landing square considered "advanced by the event"? The event moves you, so the squares you traverse (including the destination) are advanced over. So likely you ignore events at the destination as well. But need to check typical game: Many board games where you land on a "jump" square, you then move forward and possibly land on another event. Usually you would trigger the event at the landing square after the jump? The problem says "Ignore the events in the squares that are advanced by the event." This suggests that the movement due to event does not trigger any events. So if you land on an event after jumping, you ignore it. But could there be a scenario where you land on an event after jumping? That would require the destination square to be an event square, which is possible. But they said ignore. So we should treat that as not triggering.
Type 2: Get amount Ai (add to money). Type 3: Pay amount Ai (subtract). After that, money cannot be negative; if it goes below 0, set to 0.
After processing the event, you continue: If you are still not at or beyond goal? Actually, after processing an event, the turn ends? Usually, after landing on an event, you perform the action, and then if you haven't reached goal, you spin again. The example: after landing on event (type 2, get 100), they spin again. So yes, after event, you continue; you don't automatically move again unless the event type 1 moves you. After type 1 event, you might be moved forward. After that movement, does the game check if you reached goal? I think yes: if after the event you are at or beyond goal, the game ends. But we need to see if there is any additional rule: The goal is when you reach the Yth square or exceed it. So if after a type 1 advance you go to or beyond Y, then the game ends. Also if you land exactly on an event, you process it, and then if you are still not at goal, you continue spinning. So the process: Start at square 0, money=0. While position < Y: spin roulette; move forward by value; if after move position >= Y, game ends, money is current; else if position is exactly an event square (Ni), then trigger event; event may modify money or position (type 1). After event, if position >= Y, game ends; else continue loop.
But careful: type 1 event: "Advance by the specified value Ai". Does it cause an immediate additional move? So you land on an event square, then you move forward by Ai. This movement is part of the event. During that move, you ignore events (so no further triggers). After this move, if you are at or beyond Y, end. Otherwise, you stay there, and then you will spin again. There is no intermediate landing on squares that would trigger events. So it's a direct jump.
Also, note that the event squares are only at positions 1..Y-1. So after a type 1 jump, you might land exactly on an event square, but as per rule ignore, so it's not triggered.
Also, event type 2 and 3: just adjust money; position unchanged.
Now, we need expected value of final money. The state space: position (0..Y-1 maybe) and money? Money can be up to what? Possibly large? But money changes only by adding or subtracting Ai (max 100). The number of turns could be infinite if there are loops? Could there be loops? With type 1 events that advance, you always move forward? Actually type 1 moves you forward, so you never go backward. So you always move to a higher square (or same? Ai>=1, so strictly increase). Also, the roulette moves forward by positive numbers. So position is non-decreasing, and strictly increasing on each spin except maybe after event type 1 you also increase position. So overall, position is strictly increasing each turn (spin+event move). However, it's possible that after spin you land on an event, and then type 1 event moves you forward, so total movement from previous position is spin + (maybe Ai). So the position always increases. So eventually you will reach or exceed Y. So the game always terminates with probability 1.
Since money can be accumulated, but bounded? Because you may get many type 2 events? But each event square is only visited at most once? Actually you could land on the same event square multiple times? Since position only increases, you cannot go back. So each square is visited at most once. But you might land on an event square, trigger it, and then later maybe you could land on the same square again? No, because you never go backward; position only increases, so you never revisit a lower square. So each event square is triggered at most once. So total number of events triggered is at most Z. Money changes are bounded: at most sum of all type 2 Ai (<= Z*100 <= 5000) and subtract type 3 (bounded similarly). But also, negative money is clamped to 0. So money is bounded between 0 and M_max (some sum). But M_max <= 100 * 50 = 5000? Actually Z<=Y-1 <=49, so <=4900. So we could model money as part of state? However, we need expected value of final money. Might be able to compute expected money directly using dynamic programming on position only, if the effect of money is linear? But money accumulation may affect later events? Only events type 2 and 3 modify money; type 2 adds, type 3 subtracts. The subtraction could be limited by current money (since money can't go negative; if subtraction would make it negative, it becomes 0). That is a non-linear operation: max(0, money - Ai). That means expected money might depend on distribution of money. So we need to track money.
But Y <= 50, X <= 4, V <= 10. The state space: position i (0 <= i < Y). But after landing on event, we might process it and maybe change position. Actually we can treat state as (position, money). Money values might be up to maybe 5000. That's large for DP with probabilities? But we can note that money is only additive/subtractive, and clamping at 0. However, the number of distinct money values that can appear might be limited? Because each event adds or subtracts a specific amount, and you cannot get money from nowhere; only from events. So the maximum money is sum of all type 2 Ai. But that sum could be up to 4900. That's not too large? But DP over 50 positions and 5000 money values gives 250k states. Transitions: from each state, we spin roulette (X outcomes, each with probability 1/X), move to new position, maybe trigger event, resulting in new position and money. That yields a directed graph possibly with cycles? But as argued, position always increases; so in terms of (position, money), after a turn, position will increase, so there is a partial order: position strictly increases. So DP can be computed from high positions to low positions: Because from state at position p, you go to higher positions p' > p (since spin adds at least 1, and event type 1 adds at least 1). So we can compute expected final money from a given state (p, m) as: if p >= Y, final money = m (since game ends). Else, after spinning, we transition to some states (p', m') with p' > p. So we can compute by DP from Y-1 downwards. But money can increase/decrease; but p always increases, so we can compute using recursion with memoization.
But note: the number of states might be large because money is continuous. However, money values reachable from start are discrete, built from sums/differences of Ai's. But there could be many combinations, because the order matters? Actually from start, you can get to some event squares and accumulate money. Since each event is visited at most once, the total money is a sum of contributions from visited events, with subtraction clamped at 0. But because of clamping, the effect is not simply additive; the clamping could reset money to 0, which loses information. So the exact money matters.
But maybe we can compute expected final money using linear equations? Since the process is a Markov chain with states (position, money). The transition probabilities are deterministic based on roulette and events. However, because money is integer and bounded, we could in principle solve a system of equations for expected value from each state, but the number of states could be large.
But constraints: Y <= 50, X <= 4, Z <= 49. However, money can be up to 5000, which could be 50*5000 = 250k states. For each dataset, we can attempt DP with memoization and transitions? The transitions: from state (p,m), we compute expected value E(p,m). For each roulette outcome v, we compute next position p1 = p + v. Then we handle event if p1 < Y and p1 is an event square. The event is defined. After event, we get (p2, m2). Then if p2 >= Y, we get final money m2; else we need E(p2, m2). So E(p,m) = (1/X) * sum_{v} f(p,m,v) where f returns m2 if terminal else E(p2,m2).
Because p strictly increases, the recursion depth is limited. But there could be many (p,m) pairs visited from start. However, note that from a given position p, the money value can only be those that are reachable from start via some path. That might be limited. Since X <= 4, number of paths could be combinatorial but with clamping maybe moderate.
Alternatively, we could treat money as a "score" and we need expectation. Could we compute using DP on position only, tracking expected money and perhaps second moments? But clamping makes it non-linear. However, maybe the clamping only matters if money could go negative; but we can model that as max(0, m - Ai). This is like an absorbing barrier at 0. This might be manageable using DP over money distribution. But note that the state space might be large but manageable because Y is only up to 50. 250k states, each with up to X=4 transitions. That's about 1 million operations per dataset. With up to 100 datasets, that's 100 million, which is possibly okay in Python with optimization? But we must be careful about memory and time.
However, we need to consider that money can be up to 5000, but maybe typical sums are less. But worst-case Z=49, all type 2 Ai=100 gives max money 4900. That's still okay. 50 * 4901 ~ 245k states. In Python, storing a dictionary or list of that size might be okay. We can use a 2D array: for each position p (0..Y-1), we need to store E(p,m) for m values that are reachable. However, we don't know which m are reachable a priori. We could use a dictionary for each position, mapping money to expected value. But then recursion might compute many states. Alternatively, we could compute expected value via DP backwards: from positions near Y downwards, we could iterate over all possible money values up to some max, because from a given p, you might not be able to reach all m, but we could still compute E(p,m) for all m from 0..Mmax, and treat unreachable states as not needed but they might be referenced from transitions? For a given p, we need E(p,m) for m values that can appear from some prior state. But prior states could have money values that lead to p. However, if we compute from high p down to low p, we might need E(p,m) for all m because from lower p, after spin and event, you could land at p with any m (after some event adjustments). But m depends on previous events. However, we can bound m by Mmax: maximum money achievable is sum of all type 2 Ai. Also, money cannot be negative; it's clamped at 0. So m is in [0, Mmax]. That is at most 5000. That's not too huge. So we can create a DP table of size (Y) x (Mmax+1) (maybe Y is up to 50, Mmax up to 5000, product 250k). Each cell we compute expected value from that state if not yet computed. Since p always increases, we can compute in increasing order of p? But p increases, so we could compute by recursion with memoization, which will fill only reachable states. But we could also compute by iterating p from Y-1 down to 0, and for each p, for each m from 0 to Mmax, compute E(p,m) using transitions to higher p (which have been computed already because we are iterating p descending). However, we need to know for each p, m, what are the possible transitions? They depend on the roulette outcomes and events at landing squares. The events may change money and position. Since the target p' may be > p, we can compute using previously computed E(p', m') if p' < Y, or final money if p'>=Y. That is straightforward.
But there is a challenge: For a given p and m, the transition may lead to a state (p', m') where m' could be up to Mmax. However, if we iterate p from high to low, we need to have computed E(p', m') for all m' that might be reached. Since we plan to compute for all m (0..Mmax) at each p, that's fine because we compute for all m at higher p first.
But careful: The maximum money Mmax is sum of all type 2 Ai. However, there could also be type 3 events that subtract, but we don't add to Mmax from them; but we need to consider that money might exceed Mmax? Only type 2 adds money. So the maximum possible money is the sum of all type 2 Ai, because each type 2 can be triggered at most once. So that's an upper bound. However, could money become higher due to multiple visits to same type 2? No, each event square can only be triggered at most once. So Mmax is sum_{i: Ei=2} Ai. That's at most 100*50=5000. So we can set M = that sum.
But what if there are no type 2 events? Mmax=0. Then money is always 0 (since start money 0, and type 3 subtract but clamp to 0). So DP reduces to trivial.
So we can precompute Mmax. However, we must also consider that type 1 events could move you, but they don't affect money. So money only changes at event squares of type 2 or 3. So we can compute Mmax.
Now we need to compute E(p,m) for p in [0, Y-1] and m in [0, Mmax]. But note that for some (p,m) combinations, it might be unreachable, but we can still compute E(p,m) as a function; it will not be used but might be needed if transitions land there? Actually transitions from a reachable state could lead to any (p', m') that is reachable from that path; but if we compute E(p', m') for all m', we can use them regardless. However, we must be careful that the recursion formula is valid even for unreachable states? The DP is defined as the expected final money if you start from that state, regardless of whether it's reachable. So we can compute it for all states. That's fine.
But we need to ensure that the DP is well-defined: For each state, the transition probabilities are deterministic functions of v, and they lead to states with higher p, which have already been computed if we process p in decreasing order. So we can compute for p from Y-1 down to 0. For each p, we compute for m from 0..Mmax. However, within a given p, some transitions might lead to p' that is less than p? As argued, no, because moving forward by v (>=1) increases position, and event type 1 further increases position. So p' > p always. So we can compute p in descending order (starting from Y-1 down to 0). But careful: What if after spin we land on an event square at position p1 (>= p+1) and that event is type 1, which moves to p2 = p1 + Ai. It's possible that p2 <= p1? No, Ai>=1, so p2 > p1. So p2 > p1 > p. So still > p.
What about the case where after spin, p1 >= Y? Then game ends, no further state. So we treat that as immediate final money (which is m after possible events? Actually if p1 >= Y, we have reached goal, so we don't process any event? The problem says: if you exceed the goal, it is also considered as a goal. So if after move, position >= Y, game ends immediately, without processing events at the landing square? But the landing square might be >= Y, so there is no square with that number (since squares only defined up to Y). Also, if you land exactly on Y, that's goal. So events are only on squares 1..Y-1. So if after spin you go to position >= Y, you finish and no events. So that's fine.
Thus, the DP recurrence:
Define E(p, m) for 0 <= p < Y, 0 <= m <= Mmax.
For each v in V (size X, each equally probable):
p1 = p + v
if p1 >= Y:
contribution = m (since no event, money unchanged)
else:
# p1 < Y
if p1 is an event square (with type E, A):
if type == 1:
p2 = p1 + A
if p2 >= Y:
contribution = m (money unchanged, game ends after jump? Actually after jumping, you are at p2; if p2 >= Y, game ends, money is m (no change because type 1 doesn't change money))
else:
# p2 < Y, and we ignore any events at p2 (by rule). So we go to state (p2, m)
contribution = E(p2, m)
elif type == 2:
m2 = m + A
# No position change
contribution = E(p1, m2) # But careful: After event, you are still at p1. Then game continues from p1? Yes, you are at that square, and you will spin again. But wait: In the example, after landing on event (type 2), they spun again. So yes, you continue from that same square p1.
# However, need to consider that you might be at an event square after processing the event. Usually after executing the event, you stay on that square. But is there any rule that prevents triggering the same event again? Since you are already on the square and you have already triggered it, but if you stay there, will you trigger it again on subsequent turns? Typically, in board games, you only trigger when you land on it, not when you start your turn there. So if you end your turn on an event square (after processing the event), on the next turn, you will spin from that square; but if you spin and move away, you won't trigger it again unless you land on it again. However, if you stay on it (type 2/3 doesn't move you), then next turn you will start from that square. If you spin and move, you will leave it; you don't trigger it because you are not landing on it. So it's okay.
# So state after type2 is (p1, m2).
elif type == 3:
m2 = max(0, m - A)
contribution = E(p1, m2)
else:
# not an event square
contribution = E(p1, m)
End if
Then E(p, m) = average of contributions over v.
Base case: For p >= Y, the game ends immediately, but we don't define E for p>=Y. Instead we handle directly as above.
Now note: For type 2 or 3, we move to state (p1, m2). But p1 is the square we landed on, which is an event square. However, is it allowed to be at an event square at the start of a turn? Possibly yes, as per above. So we need to have E defined for that state. But careful: If we are at an event square (like after type 2 or 3), we consider that as a state. However, there might be an event at that square. But since we already processed the event when we landed, we do not process it again when we start from there. So the state (p, m) with p being an event square is legitimate; it means we are currently on that square and have already triggered its event (if any) on landing. So future moves will treat it as a normal square (since the event is only triggered upon landing). So in DP, we don't have special handling for being on an event square at the start; it's just a position.
Thus recurrence is correct.
Now we need to compute E(0,0) as answer.
Now complexity: For each dataset, we have at most Y positions (0..Y-1) and Mmax+1 money values. For each (p,m) we loop over X (max 4) outcomes, and for each we do O(1) work. So total operations O(Y * Mmax * X). With Y<=50, Mmax<=5000, X<=4 => max 1e6 operations per dataset, times 100 => 100e6, borderline but possibly okay in Python if optimized (e.g., using list of lists, precomputed transitions for each p to handle events). Also Mmax may be smaller on average. So we can implement.
But careful: Mmax might be 0, then we have only m=0. So DP is tiny.
We need to compute E(p,m) for p from Y-1 down to 0. However, note that for a given p, E(p,m) might depend on E(p, m') for the same p? For example, type 2 event: from state (p, m) after landing on p1 (event type2), we go to state (p1, m+A). That's a different m but same position p1. Since p1 > p, it's fine if we process positions descending. But type 2 event leads to same p1 (which is > p) so already computed because we compute from high to low positions. However, what about type 2 from a state where we are already at an event square? That is not a transition from start state; it's after landing. So we compute for p1 in descending order; when computing E(p, m) we need E(p1, m') where p1 > p, which are already computed if we process p descending.
But what about type 2 where after event we stay at the same square? That yields state (p1, m2) with p1 same as the landing square. But p1 > p (since p1 = p+v, and v>=1), so p1 > p. So it's still a higher position than p. So no problem.
But note: Could there be a scenario where after a type 1 jump, we land on a square p2 which is less than or equal to p? Since p2 = p1 + A, with p1 = p+v >= p+1, A>=1, so p2 >= p+2 > p. So always greater.
Thus DP in descending p works.
Now we need to handle the fact that after a type 1 jump, we ignore events at the landing square. So we treat p2 as a normal square (no event) even if it is an event square. So in DP, when we go to state (p2, m), we should not trigger any event. That's already captured because we treat (p2,m) as a state where we are at p2, and we will not trigger event unless we land on it from a spin. So it's fine.
Now one more nuance: When you land on an event square and it's type 1, you "advance by the specified value Ai". Does that movement happen immediately, and then you ignore events in the squares advanced. Also, if during this advance you pass the goal, the game ends? Yes. So we handle that.
Now we need to ensure that we correctly handle the case where after a spin, you land on an event square and it's type 2 or 3, you process it and then you are still at that square. Then you continue. That's covered.
Now about event type 1: After advancing, you might land on the goal or beyond, game ends with current money (no change). If you land on a square < Y, you go to that state.
Now about type 2 or 3: They don't change position, so after processing, you stay at that square. If that square is exactly Y? But event squares are only at 1..Y-1, so p1 < Y, so after processing you are still < Y, so continue.
Now about the rule: "Ignore the events in the squares that are advanced by the event." This we have done: for type 1, we do not process any event at the destination. However, what about the case where the type 1 advance lands exactly on an event square? According to the rule, ignore it. So we treat it as normal square. For type 2/3, there is no movement, so no advanced squares.
Now about money clamping: For type 3, if money - A < 0, set to 0.
Now we must compute expected value as an integer rounded down (floor). The description: "Please output the expected value of your money as an integer rounded down to the nearest whole number." That suggests we compute expected value as a rational maybe, but output floor of that. Since we are working with probabilities that are multiples of 1/X, and multiple steps, the expected value may be a rational number. We need to compute exactly and then floor. However, we need to be careful: Due to floating point errors, we should compute using fractions or using high-precision rational numbers. But maybe we can compute with double and floor after adding a small epsilon? But rounding down to the nearest integer means we take the floor of the exact expected value. Could be that the expected value is something like 49.9999 due to floating inaccuracies, floor would give 49 instead of 50. So we need exact rational arithmetic.
Given constraints, we can compute expected value as a rational number: numerator/denominator. However, the number of steps is unbounded but finite because each step increases position. The maximum number of steps? At most Y (since each step moves at least 1). Actually could be more if type 1 jumps? They also move forward. But each turn, you spin and move forward by at least 1 (Vi>=1). And event type 1 moves forward by at least 1, but that's part of the same turn. So total number of turns is at most Y (since each turn moves at least 1 square forward). Wait: Could you stay on same square? No, because after a spin you always move forward at least 1. So each turn (including event type 2/3) you end up at a position >= previous+1. So maximum number of turns is Y (if you always move 1). So depth of recursion is at most Y. That's fine.
Thus we can compute E(p,m) exactly as a rational number. However, the number of states (p,m) up to 250k, each storing a rational (pair of integers) could be large and computationally heavy. But maybe we can compute using floating point double with enough precision? Since Y <= 50, X <= 4, the probabilities are rational with denominator 4^k where k <= number of steps <= Y (50). So denominator can be up to 4^50 ~ 1.27e30, which is huge, but double can't represent that exactly. However, the expected value might be a rational with large denominator. But we need to output floor of exact expected value. Can we compute floor without full rational? Possibly we can compute expected value as a floating point with high precision (like using Python's fractions). But fractions could become huge and slow. However, given limited state space, we could compute using DP with memoization and rational numbers using Python's Fraction from fractions module. But 250k states each storing a Fraction with potentially huge numerator/denominator could be memory and time heavy. But maybe we can avoid rational arithmetic by noting that the DP recurrence is linear, and we can compute expected value as a rational using double and then floor? But need to be careful about rounding errors.
Another approach: Because we only need the integer part (floor), and the expected value is not extremely large (max money ~5000), maybe we can compute using double with sufficient precision? The expected value is sum over many paths of money * probability. Each path probability is of the form integer / (X^steps). The money is integer <=5000. So the expected value is rational with denominator dividing X^Y. X^Y maximum: X=4, Y=50 => 4^50 ~ 1.27e30, which is huge but the numerator is sum of integer * something, so the exact rational could be huge. But the value itself is between 0 and 5000. So the fractional part can be as fine as 1/(4^50) ~ 1e-30. Double precision (53 bits) gives about 15-16 decimal digits of precision, so it can represent numbers with granularity about 1e-15 relative. So 1e-30 is far beyond double precision. However, the expected value might have fractional part that could be very small but not necessarily representable exactly. But rounding to floor might be affected if the exact value is something like 100 - 1e-30, which would floor to 99 but double representation might round to exactly 100? But due to limited precision, we might miscompute. However, is it possible that the expected value is extremely close to an integer from below? Possibly due to many symmetric outcomes, expected value might be rational with denominator that is a power of 2 (since X may be 1,2,4). Actually X can be 1 to 4, but Vi can be any 1..10. The probabilities are 1/X each step. So each path probability is (1/X)^k where k is number of steps. So denominator is X^k. So the denominator is a power of up to 4. So the expected value is a rational with denominator a power of 2? If X=2, denominator is power of 2; X=4, also power of 2; X=1, trivial; X=3, denominator powers of 3? Actually X can be 3? X max is 4, so X can be 3. So denominator can be 3^k, not just power of 2. But still denominator is at most 4^50. The value might be a rational with denominator up to that. Could it be that the exact expected value is something like 100 - 1/3^25? That would be very close to 100 but slightly less, floor would be 99. But double may not distinguish and show 100.0 due to rounding. However, is such situation plausible given the constraints? Possibly, but we need guarantee. To be safe, we should compute exactly.
But maybe we can compute expected value using DP with high precision rational numbers that are not too big, by using fraction reduction? But the fractions can become huge. However, we can use Python's Fraction which automatically reduces. The numbers may become extremely large (numerators and denominators up to huge numbers). But with at most 250k states, each storing two integers of size up to maybe 10^30, that's huge memory and time cost. Not practical.
We need a better way.
Observing that money is integer and the expectation can be expressed as a linear function of money? Not exactly because of max(0, m-A) which is piecewise linear. But maybe we can treat money as part of state but compute expectation using DP with floating point and then floor, and ensure correctness by adding a small epsilon? Since Y and X are small, and the number of paths is finite, the expected value is a rational number with denominator D = X^N where N is max number of steps? Actually number of steps can vary, but the overall probability of any path is a product of (1/X) per spin. So denominator is at most X^Y (since maximum steps Y, but actually steps can be less than Y). So denominator is at most X^Y, which is at most 4^50 ~ 1.27e30. The fractional part may be as small as 1/D. Double precision can represent numbers with about 15-16 decimal digits accurately, so it can distinguish differences as small as about 1e-15 relative to magnitude. Since expected value magnitude is at most 5000, the absolute error from double representation of rational numbers computed via arithmetic might be on the order of magnitude of 5000 * (relative error) ~ 1e-12? Actually double has 53 bits of mantissa, so it can represent numbers with absolute precision about 2^-52 times magnitude. For numbers around 5000, that's about 5000 * 2^-52 ≈ 1e-12. That's much larger than 1/D = 1e-30. So double cannot represent the exact fraction; it will round. But the expected value we compute via DP will be using double arithmetic and accumulate many small probabilities. The error may accumulate but maybe still within 1e-9? Not guaranteed. However, we only need the floor. If the exact expected value is within 1e-12 of an integer, double rounding might cause us to output one less. But is it likely that the exact expected value is within 1e-12 of an integer? Possibly yes, because denominator can be huge and the fraction may be very close to integer. But consider the worst-case: The expected value is (some integer) - 1/D. For D up to 1e30, that's 1e-30 away from integer below. Double would round it to the integer exactly because 1e-30 is far below the representable granularity. Actually double cannot represent numbers that close to an integer; it will round to the nearest representable double, which could be exactly the integer if the fractional part is less than about 1e-16. So if exact expected value = integer - epsilon, with epsilon very small, double will likely represent it as the integer (since integer is exactly representable, and the nearest double to integer - epsilon is integer if epsilon < half of the ULP at that magnitude). The ULP for 5000 is 2^-42? Actually let's compute: The spacing between double-precision floating-point numbers around 5000 is 2^(exponent-52). 5000 is about 2^12.29 (4096 to 8192). The exponent is 12, so ULP = 2^(12-52) = 2^-40 ≈ 9.09e-13. So numbers within about 4.5e-13 of an integer might round to that integer. So if epsilon < ~5e-13, then integer - epsilon rounds to integer. That means for exact expected value = integer - 1e-30, double will be exactly integer. Then floor of that double would be integer, but exact floor would be integer-1. So we would be off by 1. So it's possible that we get wrong answer if exact expected value is just below an integer by a tiny amount.
Is it possible for expected value to be so close to an integer? Because the denominator is at most 4^50 ≈ 1.27e30, so epsilon can be as small as 1/1.27e30 ≈ 7.9e-31, which is much smaller than 5e-13. So indeed it is possible that the exact expected value is integer - 1/D, and D can be huge. So using double could cause error.
Thus we need exact rational computation. But we need to handle up to 250k states. However, we can notice that for each state (p,m), the expectation is linear in m? Not exactly because of clamping for type 3. But maybe we can transform the DP to avoid storing m as separate dimension? Let's explore structure.
The money only changes at event squares. The DP recurrence for E(p,m) can be expressed as:
E(p,m) = (1/X) sum_v f(p,m,v), where f is:
Let v be outcome.
Set pos = p + v.
If pos >= Y: return m.
Else:
if event at pos:
if type==1:
pos2 = pos + A
if pos2 >= Y: return m
else: return E(pos2, m)
elif type==2:
return E(pos, m + A)
elif type==3:
m2 = max(0, m - A)
return E(pos, m2)
else:
return E(pos, m)
Thus, the only non-linearity is the max(0, m-A) for type 3 events. This is piecewise linear: for m <= A, E(pos, 0); for m >= A, E(pos, m-A). So we can treat it as:
If m < A: return E(pos, 0)
else: return E(pos, m-A)
So the recurrence for type 3 involves a shift and clamping to zero.
Now, note that E(p,m) for a given p is a function of m that is (maybe) linear? Let's check. Suppose we ignore type 3 clamping, i.e., if we allowed negative money (or no clamp), then the recurrence would be linear in m because all operations are either add constant, subtract constant, or identity. Actually, if we had no clamping and allowed negative money, then E(p,m) would be of the form m + C(p) for some constant C(p) independent of m, because starting money m just adds to final money, since all money changes are additive and independent of m (except type 3 subtracts constant, which reduces m by A regardless). Indeed, if we define G(p) as expected additional money (over initial m) when starting from p with initial money 0, then with no clamping, E(p,m) = m + G(p). Because each transition adds or subtracts constants, and final money is m plus accumulated changes. Since the process is linear, the expectation of m + sum changes = m + expectation of sum changes.
But the clamping at zero introduces nonlinearity. However, clamping only occurs when money would go negative due to a type 3 event. So if we can guarantee that money never goes negative, then clamping is irrelevant. But it might go negative if there is a type 3 event and the current money is less than A. In such case, money becomes 0 instead of negative. So the nonlinearity is limited to cases where money could become low.
But perhaps we can still compute expectations using DP on money up to some bound, but maybe we can bound the money that matters. Because if money is large enough, the type 3 event will never cause clamping (since m >= max A for all type 3 events that could be encountered from that state). However, from a given state, future type 3 events may have different A's. But if m is sufficiently high, say >= Mmax (sum of all type 2 Ai), then it can never go negative because you could at most subtract total of all type 3 events (which may be up to sum of type 3 Ai, but we don't have bound). Actually type 3 events could subtract large amounts, but since each event can only occur once, the maximum total subtraction you might suffer from future events is sum_{i: type 3} Ai. That could be up to 5000 as well. So if m is greater than or equal to that sum, then even if you subtract all future type 3 events, you will never go below zero (since you start with m, and you might also gain from type 2 events). But careful: The order matters: if you have m high, you might encounter a type 3 event before some type 2 events that add money. But still, if m is large enough to cover the maximum possible net negative change? Actually final money could be negative only if total subtractions exceed total additions plus initial m. So if initial m >= total possible subtractions, then you will never go negative. But total possible subtractions from events reachable from a state may be less than sum of all type 3. But we can bound by S_sub = sum of all type 3 Ai in the whole board. If m >= S_sub, then from that point onward, even if you hit all type 3 events before any type 2, you'll never go negative because you subtract at most S_sub. But what about type 2 events that add money? They only help. So yes, for m >= S_sub, clamping will never occur. However, after some type 2 events, m may exceed S_sub even if initial m is lower. But we are considering state (p,m). For large m, we can treat E(p,m) = m + C(p) for some constant C(p) (the expected net change from events from that point, assuming no clamping). Because if m is high enough that clamping never triggers, then the process is linear. So we could precompute a threshold T = total sum of all type 3 Ai (or maybe the maximum cumulative subtraction possible from that state). For m >= T, E(p,m) = m + K(p) for some constant K(p). Then we can compute E(p,m) for m up to T-1 via DP, and for m >= T, use the linear formula.
But is T bounded? Type 3 Ai up to 100, and up to 49 events, so T <= 4900. So still up to 5000. That's similar to Mmax. But maybe we can reduce dimension by using linearity for m beyond some bound. However, the DP table size might still be ~ Y * T = 245k, which is manageable. But we earlier worried about rational numbers. But perhaps we can compute expectation as a rational using floating point safely because the numbers involved are not huge, but the rational accumulations could cause large denominators if we use fractions. However, maybe we can compute E(p,m) as a double with enough precision because the state space is limited and we can use high-precision decimal? Another alternative: Use DP with expected value as a rational represented as numerator/denominator but we can use Python's Fraction with caching and hope it works? Let's test approximate complexity: 250k states, each storing a Fraction. The Fraction arithmetic will involve big integers due to denominators growing. But maybe the denominators won't blow up because the transition probabilities are rational with denominator X, and we sum over few outcomes. In DP, when we compute E(p,m) = average of contributions, we will be adding Fractions and dividing by X. This will cause denominators to multiply by X each step. Since the depth of recursion could be up to Y=50, denominators could become as large as X^50 ~ 4^50 ~ 1e30, which is huge but still within Python big integers? Python can handle integers of that magnitude (up to 10^30) easily; they are about 100 bits? Actually 4^50 = 2^100 ≈ 1.27e30, which is about 100 bits. That's not huge; Python can handle 100-bit integers efficiently. But wait: 4^50 = 2^100, that's exactly 1267650600228229401496703205376? Actually 2^100 = 1.267e30, so about 100 bits. That's fine. However, the denominator might not be exactly X^50 because we reduce fractions. But if we reduce fractions, denominators could be smaller. But worst-case denominators could be powers of 2,3. 3^50 is about 7e23, also within ~80 bits? Actually 3^50 = (3^5)^10 = 243^10 ≈ 10^? Let's compute: log10(3^50) = 50log10(3) ≈ 500.4771 = 23.855, so about 10^23, which is about 78 bits? Actually 2^78 ≈ 3e23. So also around 80 bits. So denominators around 100 bits are manageable. However, fractions may involve numerators and denominators that are large but still within a few hundred bits. That should be okay in terms of storage and arithmetic.
But we need to be careful: The DP may involve many operations; 250k states * up to 4 outcomes = 1 million fraction additions and divisions. Each operation will involve big integers maybe up to a few hundred bits. That's fine in Python; 1 million big integer operations might be okay. However, we also need to consider that fractions are reduced after each operation, which involves gcd computations. That could be a bit heavier but still maybe acceptable for 100 datasets? 1 million * 100 = 100 million operations, which could be heavy. But maybe many datasets are small. Still, we can try to optimize by using DP with floats if it's safe? Let's analyze the chance of exact expected value being extremely close to an integer. With denominator up to 4^50 ~ 2^100, the fractional part can be as small as 2^{-100} ≈ 7.8e-31. Double has 53 bits of mantissa, so it can represent fractions with denominator 2^53 exactly if numerator is integer. But denominators with factors of 3 cannot be represented exactly. So the expected value could be a rational with denominator containing factor 3. In double, it will be approximated. Could the error cause floor to be wrong? Possibly if exact is 2.999999999999999... but double representation might be 3.0 exactly? For example, suppose exact expected value = 3 - 1/3^25. That's about 3 - 1.4e-12? Actually 3^25 ≈ 8.47e11, so 1/3^25 ≈ 1.18e-12. That's about 1e-12. Double ULP at 3 is 2^{-52}*4? Actually spacing around 3 is about 4.4e-16? Let's compute: double has 53 bits mantissa. For numbers around 3, the exponent is 1 (since 2^1=2, 2^2=4), so ULP = 2^(1-52) = 2^-51 ≈ 4.44e-16. So 1e-12 is much larger than half ULP (2e-16). So double could represent numbers like 3 - 1e-12 as something like 2.999999999999... but not exactly; but it will round to the nearest representable double, which will be something like 2.999999999999... The difference from 3 is > 4e-16, so it will not round to 3. So it will be less than 3, so floor will give 2. But if the epsilon is smaller than half ULP, e.g., epsilon = 1e-30, then double might round to exactly 3 because 3 - 1e-30 is within rounding to 3. But epsilon = 1/D, D up to 4^50 = 2^100, so epsilon = 2^{-100} ≈ 7.8e-31. That's less than half ULP (4e-16) for numbers around 5000? Actually for 5000, ULP ≈ 5.68e-13 (2^-40 ≈ 9e-13? Wait recalc: 5000 is between 4096 (2^12) and 8192 (2^13). The exponent is 12, so ULP = 2^(12-52)=2^-40 ≈ 9.09e-13. Half ULP ~ 4.5e-13. 7.8e-31 is far smaller, so numbers like 5000 - 7.8e-31 would be represented as exactly 5000.0 because it's within the rounding threshold. So it would round to 5000. So floor would be 5000, but exact floor would be 4999 if exact is 5000 - epsilon. So double would be wrong. Could such a case happen? Possibly. Consider a scenario where expected value = (some integer) - 1 / (4^50). That could occur if all paths yield integer money except one path with probability 1/4^50 that yields one less. That's plausible. So double would round to integer, giving wrong floor.
Thus double is not safe.
Therefore we need exact rational arithmetic. But maybe we can use integer arithmetic with fixed denominator large enough? Since we only need floor, maybe we can compute the exact expected value as a rational number using big integers, but we can avoid storing fractions for each state by computing using DP that yields rational as numerator/denominator in a common denominator? The common denominator could be X^Y (or LCM) but that could be huge. Alternatively, we can compute expected value using DP with rational numbers but we can simplify fractions. However, state count 250k, each storing two big integers up to ~100 bits; that's okay.
But is 100 bits the maximum? Actually denominators can be powers of 2,3. For X=4, denominators are powers of 2; for X=3, powers of 3. 3^50 is about 7e23, which is about 79 bits. So 100 bits is fine. But wait: When we reduce fractions, denominators may become smaller due to cancellation. However, the fractions we store for E(p,m) might be sums of fractions from deeper states. Since deeper states have denominators that are powers of X (or reduced). The sum of fractions with different denominators may lead to denominators that are multiples of those denominators. In worst case, the denominator could be LCM of many powers of X, which is still a power of X if X is prime? For X=3, denominator is power of 3; for X=4, denominator is power of 2; for X=2, power of 2; for X=1, trivial. For X=... What about X= something like 1,2,3,4. For X=... Actually X is the number of roulette outcomes, each equally likely. So probability per outcome is 1/X. So all transition probabilities are rational with denominator X. When we take expectation, we average over X outcomes: E = (1/X) * sum_{v} g_v, where g_v may be rational with denominator some power of X (since they come from deeper states). So the resulting denominator is at most X times the LCM of denominators of g_v. Since all denominators are powers of X (or reduced), the LCM will be a power of X. So denominators remain powers of X. So denominators are of the form X^k, where k is the maximum number of spins from that state to terminal. Since the maximum number of spins from a state is at most Y - p (since each spin moves at least 1), so k <= Y-p <= Y. So denominator <= X^Y. That's at most 4^50 = 2^100. So denominators are at most 2^100 (for X=4) or 3^50 (~7e23, 79 bits) or mixed if X is not prime? Actually X can be composite like 4 = 2^2, still power of 2. X could be 1,2,3,4. So denominators are powers of 2 or 3. So integer size is up to ~100 bits, which is fine.
Thus we can represent each expected value as a Fraction with numerator and denominator (both integers). However, Python's Fraction uses arbitrary-precision integers and reduces after each operation. This may be acceptable. But we need to consider performance: for each state, we compute average of up to 4 fractions. That's about 1 million fractions operations per dataset. Each operation involves addition and division (by X). Adding fractions involves cross-multiplication and gcd reduction. The numbers can be up to 100 bits, multiplication yields up to 200 bits, still fine. gcd of 200-bit numbers is not too heavy. So maybe it's okay.
But we have up to 100 datasets, worst-case each with Y=50, Mmax=5000 => 250k states, each with X=4 transitions. That's 1 million fraction ops per dataset, times 100 = 100 million fraction ops. That might be heavy