We need to parse the problem carefully. There is a frog that can change its body color to match the stone it's on? Actually, it says: "Frog can hopp on another stone if the stone has same color as its body or (i-1)th stone if it is currently on ith stone." This description is confusing. Possibly: The frog can hop to another stone if the stone has the same color as its body, OR it can hop to the (i-1)-th stone if it is currently on the i-th stone? That second part seems to allow moving one step backward regardless of color? But then the "or (i-1)th stone if it is currently on ith stone" might be a condition? Let's read: "Frog can hopp on another stone if the stone has same color as its body or (i-1)th stone if it is currently on ith stone." It likely means: The frog can hop from stone i to stone j if either:
- The color of stone j is the same as the frog's current body color (which is the color of the stone it's sitting on? Because it says "change its body's color similar to stone's color on which he sits." So when it sits on a stone, it can change to that stone's color. So presumably its body color becomes the color of the stone it's on. Then it can hop to another stone if that stone's color matches its current body color. Additionally, there is a special rule: It can also hop to the stone at index i-1 (the immediate previous stone) from stone i, regardless of color? That seems plausible. Or perhaps it means the frog can hop to a stone that has the same color as its body OR to the stone at i-1 (i.e., it can always move backward by one). But then what about moving forward? It might also be able to move forward? The rule says "or (i-1)th stone if it is currently on ith stone." That only mentions i-1, not i+1. So maybe the frog can only move leftwards (to lower index) by one step unconditionally, and to any stone of the same color (regardless of distance) when its body color matches that stone's color. That would be a typical problem: a frog can jump to any stone with the same color, and also to adjacent stones? But here it says "or (i-1)th stone if it is currently on ith stone." That's only one step left. Not right. That seems asymmetric. Could it be a misprint? Perhaps it meant: Frog can hop to another stone if the stone has same color as its body OR (i+1)th or (i-1)th stone? But the text says "or (i-1)th stone if it is currently on ith stone." That seems specific.
Let's check sample to deduce. N=6, colors: [2,3,1,3,2,4]. Queries:
- 1 0 4 => S=1, M=0, E=4. Output: 2. So from stone 1 (color 3) to stone 0 (color 2) to stone 4 (color 2)? Path: 1 -> 0 -> 4. Is that allowed? Let's test potential rules.
If frog can change color to the stone it's on, then when at 1 (color 3), body color = 3. It can jump to any stone with color 3 (positions 1? itself? maybe not, but positions: index 1 and 3 are color 3). It can also possibly jump to i-1 (0) regardless of color? That would be from 1 to 0 (color 2) - not same color, but allowed if we allow unconditional backward step. Then at 0 (color 2), body becomes 2. From 0, can jump to any stone with color 2 (positions 0,4). So 0->4 is allowed (since 4 is color 2). That yields path 1->0->4, total jumps 2. That matches output 2. So that works with rules: jump to same color anywhere, and also jump to immediate previous stone (i-1) unconditionally? But note: from 1 to 0 is i-1 (since i=1, i-1=0). That's allowed. What about jumping forward? Could we have jumped directly from 1 to something else? 1->4? 4 is color 2, not equal to body color 3, and it's not i-1 (i-1 is 0), so not allowed. So that fits.
Now second query: 2 3 5 => S=2 (color 1), M=3 (color 3), E=5 (color 4). Output -1. So can't reach. Let's check if we could possibly go from 2 to 3 to 5 under these rules. Starting at 2 (color 1). To go to M=3 (color 3). From 2, can we go to 3? Options: jump to same color as body (color 1). None other than 2? Actually other stones of color 1? Only index 2 has color 1 (since colors: 2,3,1,3,2,4; only index 2 is color 1). So only same color is itself; not helpful. Can we jump to i-1? That would be to index 1 (color 3). That's allowed (from 2 to 1). But we need to go to 3. Could we go from 2 to 1, then to 3? From 1 (color 3), body becomes 3. From 1, can jump to same color (3): indices 1 and 3. So 1->3 is allowed (jump to 3, same color). So we can go 2->1->3, that's 2 jumps to reach M=3. But we need to go from S to M to E. But we can also go directly from 2 to 3? Possibly by moving forward? If we also allowed move to i+1? The problem statement only mentions i-1, but maybe we can also move forward? Let's see: if we allowed moving to i+1 as well, from 2 to 3 would be a forward step, so allowed. Then S=2 to M=3 would be one jump. But we have to go via M, meaning we must visit M at some point (presumably we can pass through it). Then from M=3 to E=5. From 3 (color 3) body=3. Can we go to 5? Options: same color 3 -> indices 1 and 3, not 5. i-1 from 3 would be 2, not helpful. i+1? If forward allowed, from 3 to 4 (color 2). Then from 4 (color 2) to 5? From 4, if forward allowed, 4->5 (color 4) not same color, but could be allowed if forward step unconditional? Then we could go 3->4->5, 2 jumps. So total jumps S->M->E = 1+2=3? But output says -1. So that suggests forward step is not allowed, only backward step (i-1). Or maybe we misinterpret: "or (i-1)th stone if it is currently on ith stone" might be part of a condition: "the stone has same color as its body or (i-1)th stone if it is currently on ith stone." Could it mean that the frog can hop to another stone if that stone has the same color as its body OR if the frog is currently on the i-th stone, it can hop to the (i-1)-th stone (maybe regardless of color). It does not mention i+1. So indeed only a step back is allowed. So forward moves are only possible via same-color jumps? That is, you can jump to any stone of the same color (anywhere) and you can also move one step left (i-1) regardless of color. That seems odd but matches the sample: In second query, from 2 (color 1) we can go to 1 via i-1. Then from 1 (color 3) we can go to 3 via same-color jump. So we can reach M. Now from M=3 to E=5. Starting at 3 (color 3). Options: same-color jump to 1 or 3. Not to 5. i-1 step to 2. So from 3 you can only go to 2 or 1. From 2 (color 1) we can go i-1 to 1, or same-color to 2 only? Actually same-color for color 1 only index 2. So 2 can go to 1 via i-1. From 1 (color 3) can go to 1 or 3. So essentially from 3 we are stuck in the set {1,2,3}. To get to 5, we need to go to index 4 or 5. Can we reach 4? 4 has color 2. Can we get to a stone of color 2? Which indices have color 2? 0 and 4. To get to 0 or 4, we need to be on a stone with color 2 (to jump same-color) or to step left from index 1? Wait, from index 1 we could step left to 0 (i-1). That's allowed. So if we could get to index 1, we could go to 0 (color 2) via i-1. Then from 0 we could jump same-color to 4. So can we get to index 1 from 3? Yes, from 3 we can go to 1 via same-color jump (since both color 3). So path: 3 -> 1 (same color) -> 0 (i-1) -> 4 (same color). Then from 4 we need to go to 5? From 4 (color 2) we can only go to same-color: 0 or 4. Or i-1 to 3. So cannot go to 5 because 5 is color 4, not same as 2, and i-1 from 4 is 3. So we can't get to 5. Could we get to 5 via another route? Perhaps from 4 we could go to 0 then? Not helpful. Could we get to 5 from 3 via a different path: maybe 3 -> 2 (i-1) ->? 2 -> 1 (i-1) -> 0 -> 4 -> (can't go to 5). Or 3 -> 1 -> 2? Actually 1 i-1 to 0, not to 2. To go to 2 from 1: can't because no forward. So we are stuck. Thus indeed unreachable, output -1. So the rule set appears to be: from a stone i, the frog can move to:
- Any stone j (any index) such that color[j] == current body color (which equals color[i] because it changes to the stone's color when it lands? Actually the frog's body color becomes the color of the stone it sits on, so at stone i, its body color is color[i]). So it can jump to any other stone with the same color as color[i]. This includes possibly itself? Usually not counted.
- It can also jump to stone i-1 (if i>0). There is no option to jump to i+1.
Thus movement is leftwards via single steps and teleportation to any same-colored stone. That is similar to a graph where each node i has edges to: all nodes with same color as i (including i itself, but we ignore self), and also to i-1 (if i>0). However, note that when we jump to a same-colored stone, we may land on any index, possibly to the right, so we can effectively move rightwards via same-color jumps. So the graph is directed? The problem likely treats jumps as moves; we need minimal number of jumps.
But careful: The frog can change its body color only when it sits on a stone: "change its body's color similar to stone's color on which he sits." That implies that upon landing on a stone, it adopts that stone's color. So when at i, its body color is color[i]. Then it can jump to any stone with that color, or to i-1. When it lands on i-1, its body color becomes color[i-1], and then subsequent moves follow.
Thus the graph is undirected? Actually edges are defined from each node to others based on current color, but because after moving to a node, the color changes, the edges from that node are based on its color. So it's a directed graph in terms of transitions, but the edges are defined by the node's color and the rule. However, if we treat each node as a state, then from node i we have edges to: all j such that color[j] == color[i], and also to i-1 (if exists). So it's a directed graph but edges from i to j exist under those conditions. Since the graph is defined based on node properties, we can treat it as an unweighted directed graph (or maybe undirected if some edges are symmetric). Let's check symmetry: From i to i-1 is always allowed, but what about from i-1 to i? That would be a move from i-1 to i: Is that allowed? From i-1, allowed moves are to same color as color[i-1] and to (i-1)-1 = i-2. So from i-1, moving to i is not allowed unless color[i] == color[i-1] or i == (i-1)-1? No, i is not i-2, so only if colors match. So i-1 -> i is not necessarily allowed. So the graph is not symmetric. So we need to consider directed edges.
But wait: Is the move to i-1 considered unconditional? Yes, as per description: "or (i-1)th stone if it is currently on ith stone." So from i, you can always go to i-1 regardless of colors. That is a directed edge from i to i-1. There is no rule allowing moving to i+1. So the graph is directed: leftward step edges, and same-color edges (which are bidirectional? Actually if color[i]==color[j], then from i you can jump to j, and from j you can jump to i because both share the same color, so edges are bidirectional for same-color connections. So those edges are undirected. So overall graph is mixed: undirected edges among all nodes of same color, and directed edges from each node i to i-1 (except i=0).
Thus the problem reduces to: Given N up to 1e5, Q up to 50 queries. For each query (S, M, E), we need the minimum number of jumps to go from S to E, passing through M at some point (i.e., the path must include M). Possibly we can interpret as minimal jumps from S to E that also visit M (maybe in any order? But "to reach E from S via M" suggests starting at S, must go to M, and then from M to E. Typically "via M" means you must pass through M; i.e., path S -> ... -> M -> ... -> E. Could also be interpreted as S to M then M to E, i.e., sequential. It likely means the frog must go from S to E, but must also touch stone M along the way. But the minimum jumps from S to E might not go through M; we need the minimal jumps that include M. That is like the shortest path from S to E that goes through M, which equals shortest path from S to M plus shortest path from M to E, if the graph is such that shortest paths can be combined without overlapping (i.e., if the shortest S->M and M->E are vertex-disjoint except at M, but even if they overlap, the concatenation yields a path that goes through M; but it might not be the shortest overall through M because there could be a path that is not simply concatenation of two independent shortest paths if they share edges? Actually for any path from S to E that passes through M, it can be split into S->M and M->E subpaths. The length of the path is length(S->M segment) + length(M->E segment). The minimal total length that goes through M is min over all possible paths: dist(S, M) + dist(M, E) where dist is shortest path distance in the directed graph? However, note that the concatenation of two shortest paths yields a valid path from S to E that passes through M, so the minimal total distance cannot be less than dist(S, M) + dist(M, E). But could there be a path that is shorter than the sum of the two independent shortest paths? That would require that the optimal S->E path that goes through M does not necessarily use the shortest S->M and shortest M->E individually? Actually if we take any path from S to E via M, the portion from S to M is some path with length L1, and from M to E is some path with length L2. The total is L1+L2. The minimal possible total is min_{paths P from S to M} (len(P) + min_{paths Q from M to E} len(Q))? But the min of sum is at most min_{P} len(P) + min_{Q} len(Q) = dist(S,M)+dist(M,E). However, could there be a path where the segments share some part that reduces total? Since they must meet at M, the S->M part and M->E part are disjoint in time but could share vertices/edges? They could overlap if the path goes S->...->X->M->X->...->E? That would revisit X, but then the path would go through M and then maybe go back. But the length would be len(S->M) + len(M->E). Even if they share vertices, it's still the sum of lengths of two subpaths. So the minimal total length is indeed dist(S,M)+dist(M,E) if the graph is such that we can combine any two paths without conflict. However, is there any restriction that the frog cannot use the same stone multiple times? Typically shortest path in unweighted graph doesn't prohibit revisiting vertices; but if revisiting is allowed, the shortest path distances are still defined (allowing cycles) and the concatenation of two shortest paths might have overlapping vertices, but that still yields a valid walk, not necessarily a simple path, but it's allowed? Usually in such problems, the frog can jump arbitrarily, and revisiting stones is allowed (nothing says it's prohibited). So the minimal number of jumps from S to E that visits M would be at most dist(S,M)+dist(M,E). However, could there be a shorter walk that goes through M but not as separate two independent shortest paths? Consider if there is a path from S to E that goes through M but the S->M part is not the shortest, but the M->E part is much shorter, but total might be less? No, because if there is a shorter total, then by taking the S->M part of that walk, we have a path from S to M of length L1, and the M->E part of length L2, total = L1+L2. Since dist(S,M) <= L1 and dist(M,E) <= L2, we have dist(S,M)+dist(M,E) <= L1+L2. So the sum of distances is a lower bound, and concatenation yields exactly that sum. So minimal total = dist(S,M) + dist(M,E). Provided that the distances are defined (i.e., reachable). If either is unreachable, total is unreachable.
Thus for each query we need to compute d(S,M) and d(M,E). If either is infinite, output -1; else output d(S,M)+d(M,E). However, careful: Could the path require that we visit M exactly once? Usually "via M" means you must go through M, but you could pass through M earlier and then later go to E; the concatenation of shortest paths gives a walk that may pass through M multiple times? Actually the concatenation of a shortest S->M path and a shortest M->E path yields a walk that starts at S, goes to M, then continues from M to E. It visits M at the junction point exactly once (if the two paths are simple and do not revisit M). But if the M->E path might also go through M again? That would be wasteful; we could truncate. So we can assume there exist optimal simple walks that do not revisit M except at the junction. So sum of distances works.
Thus the problem reduces to computing shortest distances in this directed graph.
But Q is small (<=50) while N up to 1e5, so we can afford to do BFS from source up to 2*Q times? Possibly 50 queries, each might require distances from S to M and M to E. That's up to 100 BFS runs. BFS on graph with N nodes and edges: each node has an edge to i-1 (1 edge) and edges to all nodes of same color (could be many). If we construct adjacency list explicitly, it could be dense for colors that appear many times. For example, if all stones have same color, then each node connects to all N-1 other nodes, leading to O(N^2) edges. That's too large. So we need to handle same-color jumps efficiently, using a trick: we can treat color groups as "teleportation" edges that can be traversed in one step to any node of that color. This is like having a super-node for each color, connecting to all nodes of that color with zero cost? Actually it's one jump. Typically, for such problems, we can model using BFS with an optimization: when we visit a node of a certain color for the first time, we can "activate" the color group and add all nodes of that color to the queue (since from any node of that color, you can jump to all others in one step). But careful: edges are undirected among same color, but also we have the left step edges.
One common technique: Build graph where each node i is connected to i-1 (if exists) and to a color virtual node? Represent each color as a virtual node; then from i to its color node cost 0? But jumping from i to another same-color j is one jump, but we can model as i -> color_node (cost 0?) and color_node -> j (cost 1)? Or i -> color_node (cost 0) and color_node -> j (cost 0)? That would yield 0 cost, but we need 1 jump. Actually, we can treat the teleportation as: from i, you can go to any j with same color in one jump. That's like a clique with edge weight 1. To optimize, we can use BFS with state and "color visited" flag: when we first encounter a color, we enqueue all stones of that color (since they become reachable in one additional jump from the current node). But we must be careful not to repeatedly add them.
Standard approach for problems like "jump to any index with same value" plus adjacent moves: do BFS on indices, and maintain for each value (color) whether we have already "used" its teleportation. When we pop a node u, we consider:
- Move to u-1 if not visited.
- For teleportation: if the color of u hasn't been "expanded", then we add all nodes with that color (except u itself) to the queue (or mark them visited) with distance dist[u] + 1. Then mark that color as expanded to avoid re-adding later. Because from any node of that color, we can jump to all other nodes of that color in one step. So once we've visited one node of that color, all others become reachable with an extra step from that node. But careful: The teleportation is symmetric; if we later visit another node of the same color via a different path, we should not re-add the group because they are already visited (or we may get a shorter distance via this new node? However, since all nodes in the group are reachable from any visited node of that group in one step, if the group hasn't been expanded yet, expanding from the first visited node gives them distance d+1. If we later visit another node of the same color with distance d' > d, then adding the group from that node would give them distance d'+1 which is larger, so not beneficial. If we later visit a node of that color with distance d' < d, that would be impossible because once we visited a node of that color, we could have expanded from it, and all nodes in that group would have distance <= d+1. If we later find a node of that color with distance less than d, that would mean we reached it via a different path without using the group expansion, which could be shorter. But could that happen? Let's think: suppose we have color C. We first reach a node x of color C with distance d_x. We then expand all other nodes of color C, giving them distance d_x+1. Now, if there is a node y of color C that we later reach from a different path with distance d_y < d_x+1, could that happen? Possibly if y was already visited with distance d_x+1, then d_y would be >= that because BFS ensures shortest distances. But if y was not visited before (maybe we didn't expand because we only expanded from x? Actually we would have added all nodes of color C when we first expanded from x, so they would be visited with distance d_x+1. When BFS continues, we might later find a shorter path to y? That would contradict the fact that BFS from source explores in increasing distance order; if we visited y with distance d_x+1, then any alternative path to y would have distance >= d_x+1 if BFS is done correctly. However, there is a nuance: the expansion from x adds all nodes of color C at distance d_x+1. If there exists a node z of color C that can be reached from source in fewer than d_x+1 steps without using the teleportation from x, then BFS would have visited z before we processed x? Actually, BFS processes nodes in order of distance. If such a shorter path exists, we would have visited z earlier, and since z is of color C, we would have expanded from z first, giving all other nodes distance d_z+1 which would be <= d_x (since d_z < d_x+1, maybe d_z <= d_x). But if we expanded from z first, then when we later process x, the color would already be marked expanded, so no expansion from x. So the algorithm that expands a color only the first time we encounter any node of that color ensures that the distances assigned to other nodes of that color are as low as possible. So it's correct to expand only once per color.
Thus BFS can be done in O(N + total left edges + processing each node once and each color group once). Since each node belongs to exactly one color group, the total additions from color expansions is O(N) overall (each node added to queue via its color at most once). Additionally, we process the left edge from each node: when we pop a node, we consider its left neighbor (i-1). So BFS runs in O(N) per source, given we have precomputed lists of nodes per color.
But note that the graph is directed: left edge from i to i-1 only, not right. However, teleportation edges are undirected. So BFS from a source will explore using these edges. Since left edges only go left, BFS may not be able to reach nodes to the right except via teleportation to same-color nodes that may be to the right. So it's fine.
Now, Q is up to 50, N up to 1e5, so 50 BFS runs each O(N) = 5e6, which is okay.
But we need to compute distances from S to M and M to E. So we could run BFS from S to compute distances to all nodes? That would give d(S, *) and then also d(M, *) if we BFS from M. So per query we need two BFS runs? That would be 100 BFS runs => 100 * 1e5 = 1e7, still okay. However, we must consider that each BFS involves queue operations and expansions. 10 million operations is fine in 1-2 seconds in C++ but in Python might be borderline but likely okay with efficient implementation. N=1e5, Q=50, 100 BFS => 10 million node visits, each visit processing left neighbor and maybe color expansion. However, color expansion may add many nodes at once, but each node is added via expansion only once per BFS, and also via left neighbor. So total operations per BFS O(N + number of colors visited). With N=1e5, total ~1e5 per BFS, so 100 BFS = 10 million. Python can handle 10 million operations if optimized (using deque, list, sets). But we must be careful: when expanding a color, we need to iterate over all nodes of that color and add them to queue if not visited. If we do that each time we expand a color, and a color may have many nodes (like 1e5 of same color), then one BFS could add all nodes in one go, which is O(N). That's fine as total across BFS.
However, there is a nuance: the graph is directed? The left edge is directed, but BFS treats it as an outgoing edge from i to i-1. That is fine.
But one important question: Is the frog allowed to jump to any stone with same color as its body? The statement says: "Frog can hopp on another stone if the stone has same color as its body". That suggests it can jump directly to any other stone (any index) with the same color. It doesn't say there is any distance limitation. So yes, it's a full clique.
Now verify with sample: BFS from S=1 to compute d(1,0) and d(1,4)? Actually we need d(S,M) + d(M,E). For query 1: S=1, M=0, E=4. Compute d(1,0). Starting at 1. Moves: from 1 can go to i-1=0, so distance 1. So d(1,0)=1. d(0,4): from 0 can go to same color (2) -> indices 0 and 4. So 0->4 distance 1. Sum=2. Good.
Second query: S=2, M=3, E=5. d(2,3): from 2, moves: i-1 -> 1; from 1 same color -> 3; so distance 2? Actually 2->1 (1), 1->3 (2) => d=2. Or 2->? Could there be a direct? 2 can't go to 3 because not same color and not left. So d=2. d(3,5): from 3, can go to i-1=2 (1), from 2 left to 1 (2), from 1 left to 0 (3), from 0 same color to 4 (4), from 4 left to 3? That's backtrack. Could there be a shorter? Also from 3 same color to 1 (1), then from 1 left to 0 (2), then 0 same color to 4 (3). From 4 can't go to 5. So distance to 5 is infinite. So d(3,5) unreachable -> -1. Good.
Thus our interpretation matches.
Now we need to implement BFS from a given source to compute distances to all nodes (or at least to target nodes). Since Q is small, we can do BFS from each source (S and M) per query. But we could also precompute something? However, the queries have different S, M, E. So BFS per source is fine.
Potential pitfalls:
- The graph is directed: left edge only. Teleportation edges are undirected (i.e., if color[i]==color[j], then from i you can go to j, and from j to i). So in BFS, from a node i, we need to consider:
- neighbor i-1 if i>0.
- all nodes j (j != i) with color[i] (same color). That includes both left and right indices.
- However, note that teleportation is instantaneous from i to any j of same color. So when we expand from i, we could add all those j at distance d+1. But careful: If we add all j, we might add many nodes, but that's okay if we do it only once per color.
Implementation approach for BFS from source s:
- We'll have an array dist of size N, initialized to -1.
- queue = deque()
- dist[s] = 0; queue.append(s)
- We'll maintain a boolean array or set for colors that have been "expanded". Since colors are up to 100 (the problem says "only 1 to 100 different colors", but actually "There are N colorful stones lying in a row, but of only 1 to 100 different colors." That means the colors are integers from 1 to 100? The sample includes numbers like 2,3,1,3,2,4. So colors are between 1 and 100 inclusive? They said "only 1 to 100 different colors", meaning the number of distinct colors is between 1 and 100. So the color values could be up to 100? Actually they say "but of only 1 to 100 different colors." That likely means there are at most 100 distinct colors, but the actual color numbers could be up to something? Usually such constraints: each color is an integer between 1 and 100. That is a small range. That's important! Because if colors are only up to 100, we can have at most 100 color groups. So per BFS, the expansion of a color is limited by number of nodes of that color, which could be large, but there are at most 100 colors. That's helpful. However, earlier I thought up to 1e5 colors, but actually distinct colors <= 100. That simplifies.
Given that, we could also precompute for each color the list of indices. That's needed.
Now BFS:
while queue:
u = queue.popleft()
d = dist[u]
# Left neighbor
if u > 0 and dist[u-1] == -1:
dist[u-1] = d+1
queue.append(u-1)
# Teleportation: all stones with same color as u
c = color[u]
if not color_used[c]:
# for each index v in color_indices[c]:
for v in color_indices[c]:
if dist[v] == -1:
dist[v] = d+1
queue.append(v)
color_used[c] = True
Note: We must not include u itself; but if we iterate over all indices of color c, we will also encounter u which already has dist = d (0 or something). Since we check dist[v]==-1, we skip u. So it's fine.
But careful: When we expand a color, we add all nodes of that color in one go. However, consider a scenario: we visit node u with distance d, and we expand its color, setting all other nodes of that color to d+1. That's correct because from u you can jump to any of them in one step. However, what about the node u-1? It might also have the same color as u. If we expand color from u, we will set dist for u-1 to d+1, but maybe there is a shorter path to u-1 via left step? Actually from u, we also have left step to u-1 with distance d+1 as well. So both give same distance. That's fine. But if we had already set dist[u-1] via left step before expanding color, it will already be d+1 (since we process left neighbor before color expansion? Not necessarily; order doesn't matter, we will check dist before assigning). If left neighbor was set earlier (maybe from another path) with a smaller distance? Could there be a smaller distance? From u, left step gives d+1. If some other node reached u-1 earlier with smaller distance, then dist[u-1] would already be < d+1, so we won't override. So it's fine.
But one nuance: The teleportation edges are undirected, but our expansion from the first node of a color might assign distances to other nodes that are not optimal if there exists a path that reaches one of those nodes via a different route with less than d+1 steps without using that color. However, since we are doing BFS in increasing distance order, the first time we encounter any node of that color, that node's distance d is the shortest distance to that color group. Because if there is any node of that color reachable with distance less than d, it would have been popped earlier, and then its color expansion would have happened earlier, giving all nodes of that color distance <= (that smaller distance) +1, which is <= d. So by the time we pop u, if its color hasn't been expanded, that means no node of that color has been visited earlier. Thus d is the minimum distance to any node of that color. So d is optimal. Then adding all other nodes with d+1 is optimal for them because any path to them must go through some node of that color first (since teleportation is the only way to get to them aside from left steps, but left steps only move left, so to get to a node that is to the right or far away, you might need teleportation). Actually could there be a path to a node of that color that doesn't involve first landing on some node of that color? For example, to reach node v of color c, you could come from v+1 via left step (since from v+1 you can go to v if you move left? Wait, from v+1 you can go to v because left step from v+1 goes to v. But that requires you to be at v+1. And to get to v+1, you might not have visited any node of color c yet. So it's possible that the first time you reach any node of color c is via left step from a neighbor that is not of that color. That would mean you directly land on v with some distance d_v. At that moment, v is of color c, and we will expand color c if not already expanded. This expansion will assign distances to all other nodes of that color as d_v+1. That is optimal? Suppose there is a node w of same color that could be reached with a distance less than d_v+1 via some other path that does not involve teleportation? For w to be reached without teleportation, it must be reached via left steps only, but left steps only go leftwards. So if w is to the right of the visited nodes, it's impossible to reach it without teleportation because you cannot go right via left steps. However, you could reach w via left steps from further right? But to go right you need teleportation. So essentially, without teleportation, the only way to move is leftwards (decreasing index). So any node to the right of the starting point cannot be reached unless there is a teleportation to a node with a color that appears to the right. So the BFS with color expansion seems correct.
We must be careful with the directed nature of left steps. BFS from a source may only reach nodes that are left of the source via left steps, but via teleportation it can jump to any index with same color as some visited node. So overall reachable set could be many.
Edge Cases: The frog starts at S. It can also jump to any same-colored stone, including those to the right. So reachable set could be whole graph if the color groups connect everything.
Now compute distances d(S,M) and d(M,E). Use BFS from S to get distance to M. Then BFS from M to get distance to E. Add them. If either is -1 (unreachable), output -1.
Complexities: BFS from source: O(N + sum of sizes of color groups expanded). Since each node is enqueued at most once (either via left step or color expansion), and each color group is expanded at most once, we will iterate over all nodes of that group when expanding. But note: when we expand a color group, we iterate over all indices of that color, even if some of them have already been visited (dist != -1). However, we only enqueue those not visited. But iterating over all indices of that color could be O(size of group). Since we expand each color at most once per BFS, total iteration over nodes due to color expansions across the entire BFS is O(N) because each node belongs to exactly one color and we process its list only when that color is expanded. So overall BFS O(N). However, if we iterate over the whole list even for visited nodes, that's fine.
Implementation details: We'll precompute color_to_indices: a dictionary or list of lists, with color numbers (which are up to maybe 100, but could be larger? The problem says "only 1 to 100 different colors". I'll assume color values are between 1 and 100 inclusive, but perhaps they could be up to 10^9? The statement says "but of only 1 to 100 different colors." It likely means there are at most 100 distinct colors, but the actual numbers could be up to something. But we can map them to small IDs. For safety, we can map distinct colors to IDs 0..C-1, where C <= 100. Or we can just use the given numbers as keys, assuming they are small. N up to 1e5, Q up to 50.
Now, for each BFS, we need a fresh dist array (size N) and a visited flag per color (size C). Since C is small (<=100), we can use a boolean list of length C. Alternatively, we could use a set.
Now let's test with sample.
Now consider potential pitfalls: The move to i-1 is allowed only if i>0. Also, what about i=0? Then no left move.
Also, note that teleportation from i can go to any stone of same color, including those with index less than i. So it's fine.
Now, about "minimum no. of jumps he needs to take to reach E from S via M." Could there be a path that goes S->...->E that passes through M but not necessarily in the order S->M->E? It says "reach E from S via M", which I interpret as start at S, end at E, and must pass through M along the way. Typically that implies S->...->M->...->E. However, could it be that the frog could go S->...->E and also pass M, but not necessarily M after S? Since it's a path from S to E, any path from S to E that includes M works. Because it's a directed graph? But it's not necessarily strongly connected; but S->...->M->...->E is natural. Since we need to output min jumps, we can compute dist(S,M)+dist(M,E) as argued. But is it possible that the optimal path visits M more than once or goes S->...->E and then to M? No, because path must end at E, so M must be before E.
Thus our approach seems correct.
Now let's test more scenarios.
Edge Cases: If S, M, E are same? Then d(S,M)=0, d(M,E)=0, sum=0. That's fine.
What if M is unreachable from S, or E unreachable from M? Output -1.
Now we should also consider if there is any possibility of a path that uses M not as a splitting point but where the optimal path from S to E that passes through M is shorter than sum of shortest S->M and M->E? That's impossible as argued because any path from S to E that passes through M can be split at first occurrence of M (since we can stop at M and then continue). That yields two paths S->M and M->E (the latter might not be simple, but length is at least dist(S,M) and dist(M,E)). So sum of distances is a lower bound, and achievable if we take the shortest S->M and then shortest M->E, but careful: concatenating two shortest paths might create a walk that repeats vertices, but does it guarantee that the resulting walk is valid? Since the graph is directed? The edges are: from i to i-1 (directed), and from i to j if color[i]==color[j] (undirected). So if we take a shortest path from S to M (say path P1) and a shortest path from M to E (path P2), we can concatenate them to form a walk from S to E that goes through M. However, we must ensure that the transitions are valid at the junction: after finishing P1 we are at M, then we start P2 from M. That's fine. The walk may include cycles, but that's allowed. So the concatenated walk is a valid sequence of jumps. So the distance sum is achievable. So minimal total = dist(S,M)+dist(M,E). Good.
Now implement BFS.
Pseudo:
from collections import deque
def bfs(start):
N = len(colors)
dist = [-1]*N
color_used = [False]*MAX_COLOR_ID # but we need mapping
queue = deque()
dist[start] = 0
queue.append(start)
while queue:
u = queue.popleft()
d = dist[u]
# left neighbor
if u > 0 and dist[u-1] == -1:
dist[u-1] = d+1
queue.append(u-1)
# teleportation via color
c = color_id[u] # we can map to small ints
if not color_used[c]:
for v in color_groups[c]:
if dist[v] == -1:
dist[v] = d+1
queue.append(v)
color_used[c] = True
return dist
We need to precompute color_groups as list of lists, indexed by color ID.
Mapping: colors given as integers. They may not be consecutive from 1 to 100; we can compress them.
Since Q up to 50, we could run bfs for each query for source S and M. But we can also cache BFS results per source because multiple queries might reuse same source? Q is small, caching not necessary.
But BFS from each source is O(N). 100 BFS * 1e5 = 10^7, plus operations for color expansions that iterate over groups once per BFS. However, when expanding a color, we iterate over all nodes of that color, even if many of them are already visited? In our code, we check dist[v]==-1 before enqueuing, but we still loop over all v in the group. Since each BFS expands each color at most once, and each node appears in exactly one group, total iterations over nodes across all color expansions in one BFS is sum of sizes of all groups = N. So BFS total operations: each node may be processed from queue (pop) once; each pop does constant work (left neighbor and maybe color expansion). The color expansion loops over all nodes of that color, which totals O(N) across the BFS. So overall BFS is O(N). So 100 BFS = 10 million node visits and about 10 million extra loop iterations (for color expansions) which is fine.
But note: The BFS may expand a color group that is large, say size N (if all stones same color). Then in that BFS, when we first encounter any node of that color, we will iterate over all N nodes. That's O(N). That's okay.
Now we must be careful about recursion depth? Not using recursion.
Now confirm that the BFS correctly accounts for the fact that teleportation edges are undirected. Our approach of expanding color group when first visited ensures that once any node of that color is reached, all others get distance d+1. However, consider this: From node u, you can jump to any node v of same color. But suppose we later reach another node w of the same color via a shorter distance? That's not possible because if we expanded from the first node u, we assigned distances to all other nodes as d_u+1. If there existed a shorter path to some v (with distance less than d_u+1), that path would have to go through some node x of that color that is reached earlier? But the first node of that color reached is u with distance d_u. If there were a node x of that color reachable with distance < d_u, then it would have been visited earlier, and we would have expanded from x instead, giving distances d_x+1 <= d_u. So indeed d_u is minimal distance to that color. So the assignment d_u+1 is optimal for other nodes.
One more nuance: The teleportation edges are symmetric, but our expansion from the first visited node adds all others at distance d+1. But what about the first visited node itself? It's already visited. For other nodes, if they were already visited via other means (e.g., left steps) with distance <= d+1, they won't be updated. That's fine.
Now about the left step: It is directed from i to i-1. Could there be a situation where a node is reachable via a left step that is part of a color expansion that hasn't happened yet? That's fine.
Now we need to compute dist(S, M) and dist(M, E). However, note that our BFS from S computes distances to all nodes. So we can just retrieve dist[M]. Similarly for BFS from M.
Thus algorithm per query:
- Run bfs(S) -> distS
- if distS[M] == -1: answer = -1
- else:
run bfs(M) -> distM
if distM[E] == -1: answer = -1
else answer = distS[M] + distM[E]
Alternatively, we could combine into one BFS that computes distances from S to all, and from M to all separately.
Now complexity: 2 BFS per query, up to 100 BFS. Each BFS O(N). With N=1e5, total operations ~10^7, fine.
Now we need to implement.
Potential memory: dist arrays of size N per BFS; we can allocate fresh each time, but Python may be slow if we allocate many large lists. We could reuse one list and reset. Since Q is only 50, allocating 250 = 100 lists of size 1e5 each would be 1001e5*8 bytes ~80 MB if floats? Actually each integer takes more memory, but typical Python int is 28 bytes. 100 * 1e5 * 28 = 280 million bytes = 280 MB, too high. So we cannot keep all dist arrays. Instead, we should allocate per BFS and discard after use, or reuse a single list and reinitialize with -1 each BFS. Reinitializing a list of length N with [-1]*N each BFS costs O(N) which is already part of BFS; it's fine. But we also need a visited flag per color (size <=100) which is tiny.
But we might allocate a new list each BFS, that's O(N) time for initialization, which is okay. But we need to ensure we don't allocate many large lists simultaneously. We can just compute distS = bfs(S); then compute distM = bfs(M); then compute answer, and discard both. Python's garbage collector will free memory, but we can reuse a single list by reinitializing? Simpler: define a function bfs(start) that creates dist = [-1]*N and does BFS, returns dist. That will allocate a new list each call. With up to 100 calls, we might allocate 100 * 1e5 = 10 million integers? Actually each list holds N integers (1e5). 100 such lists would be 10 million integers; each Python integer is about 28 bytes, that's 280 MB. However, they are not all alive at the same time if we call bfs sequentially and don't keep the results after using them? In the loop for each query, we compute distS, use it, then compute distM, use it, then discard before next query. At any moment, we have at most two dist arrays (distS and distM) alive. That's 2 * 1e5 = 200k integers, which is about 5.6 MB, fine. So no problem.
Now we need to read input, precompute color groups.
Implementation steps:
-
Read N
-
Read list of N integers (colors)
-
Build mapping from color to list of indices. Since colors up to maybe 100, we can use dictionary mapping color -> list. But we can also compress to contiguous IDs: use dict to assign integer id per distinct color.
-
color_groups: list of lists, each list contains indices where that color appears.
-
Also create an array color_id of length N: the compressed color id for each index.
-
Read Q
-
For each query (S, M, E):
- d1 = bfs(S)[M]; if -1: print -1; continue
- d2 = bfs(M)[E]; if -1: print -1; else print d1+d2
Now, check correctness with sample.
But we must ensure BFS from a source correctly handles teleportation: when we pop a node, we check if its color has been used; if not, we enqueue all indices of that color with distance d+1, but also we need to consider that the current node might itself be in that group, but we skip because visited.
But there is a subtlety: The teleportation from node u to any node v of same color is a one-step move. However, consider that we might also teleport from v back to u? That's already covered when we later pop v and expand its color (if not already expanded). But if we expanded color when we first visited u, we set all v to distance