We are given a directed graph with N vertices, M edges. Home S, work T. We are allowed to flip the direction of at most one edge (i.e., change its direction to opposite). After possibly flipping one edge (or none), we want the shortest path from S to T (in terms of number of edges, unweighted). If flipping an edge can reduce the distance, we need to output the shortest distance (number of edges) after flipping the best edge, and the index of that edge (edges are given in order from 1 to M). If multiple edges yield the same shortest distance, choose the smallest index. If no flip yields a shorter distance than the original (i.e., original distance is already minimal? Actually we need to compute the best possible distance after at most one flip; if the original distance is already the minimal possible? But we must output distance and road number: if no direction change results in a shorter route, print 0 as the road number. That means if the best distance is the original distance (or maybe if we cannot improve), we output the original distance? Wait: The problem says: "If no direction change results in a shorter route, print 0 as the road number." So we always output the shortest distance after at most one flip, and the road number (or 0). So we need to compute the minimum distance achievable by flipping at most one edge. If flipping no edge (i.e., original) gives the minimum distance among all possibilities (including flips), then the road number is 0. But it's possible that flipping an edge could produce a distance equal to the original, but that wouldn't be "shorter". The phrase "no direction change results in a shorter route" means that if we cannot get a distance less than the original distance, we output 0. So if the original distance is D0, and the minimal achievable distance D_min = D0 (including no flip or flips that don't improve), then we output D0 0. But if there is a flip that gives distance D_min = D0 but there is also some flip that gives the same distance? Actually if D_min = D0 and there exists a flip that also yields D0 (maybe the same as original), but we only care about "shorter". Since no flip yields a strictly shorter distance, we output 0. So we only consider flips that yield a distance less than the original. But is it possible that original distance is infinite (no path) and flipping some edge creates a path? Then the new distance is finite, which is certainly shorter (since infinite is not a number). So then we output that distance and the road number. So we need to handle unreachable cases.
We have unweighted directed graph, we can flip one edge. Need to compute minimal possible distance from S to T after flipping at most one edge.
Constraints: N up to 1000, M up to 10000. Could do something like: For each edge e = (u->v), if we flip it, it becomes (v->u). Then we want the distance from S to T in this modified graph. Doing this for each edge individually would be O(M * (N+M)) which could be 1e4 * 1e4 = 1e8, maybe borderline but with N=1000, M=10000, BFS is O(N+M) ~ 11000, times 10000 = 110 million, which might be okay in C++ but we need to be careful. However the problem might require a more efficient approach.
Alternatively, we can precompute distances from S to all nodes in the original graph (forward distances) and distances from all nodes to T in the original graph (reverse distances). Then, when we flip an edge (u->v), the new graph differs only in that edge direction is reversed. So to compute the new shortest path from S to T, there are two possibilities: either the shortest path does not use this flipped edge, in which case its length is the original distance D0 (if S->T exists) but we are considering a scenario where we flipped, but the path might avoid it. Or it uses the flipped edge (which now goes v->u). Since we flipped, the direction is reversed, so the edge can be traversed from v to u. So any S->T path that uses this flipped edge would go from S to v (using original edges, maybe including the edge itself? But the edge is flipped, so we cannot use it in original direction; but we could use it in the opposite direction. So a path could be S -> ... -> v -> (flipped) u -> ... -> T. So length = dist_original(S, v) + 1 + dist_original(u, T). However careful: The original distances computed on the original graph, but after flipping, the edge direction is reversed. However the rest of the graph remains the same. So dist_original(S, v) is the distance from S to v using original directed edges (without flipping). But note: Could the path from S to v use the flipped edge? That would require going through that edge in its original direction u->v, but after flip, that direction is no longer allowed, so we must not use it in that direction. So dist_original(S, v) as computed on original graph might include that edge. But after flipping, that edge is reversed, so the original direction is gone; so the distance from S to v in the modified graph might be different if the shortest path in original used that edge. However we can still compute dist_original(S, v) in the graph without the flipped edge? But we can't simply use original distances because they assume the edge is present in its original direction. But if the shortest path from S to v in original uses that edge (u->v), then after flipping, that path is no longer valid. However there might be other paths to v. So using original distance as an upper bound is fine, but to compute exact shortest distance after flip, we need to consider that the distances to nodes might change because the edge direction changed. However the effect is local; we are allowed to use the flipped edge only in the reverse direction. The new shortest path from S to T could potentially use the flipped edge in the reverse direction, or not use it at all. But also, the flip could affect paths that don't directly include the edge but might affect connectivity because some node's distance changes due to the removal of the original direction? For example, if some node v was reachable only via that edge (u->v), then after flip, v might become unreachable from S. But then if we need to go from S to v for some path that uses the flipped edge in reverse (v->u), that could be problematic. So we need to compute distances in the modified graph exactly. However can we compute the new distance from S to T efficiently for each edge using precomputed distances from both directions? Usually, for edge reversals, we can compute the effect by considering paths that use the reversed edge. However the removal of the original direction might break some original shortest paths that don't involve the reversed edge? Actually if a shortest path from S to T in the original graph does not use the edge being flipped, then after flipping, that path remains unchanged, so the distance is at most original distance. So the minimal distance after flip is at most D0 (or infinite if original unreachable). However if we flip an edge, the new graph might have a path that is shorter than original (using the reversed edge), but the original direction removal could only increase distances for paths that relied on that edge. Since we are looking for the minimum possible distance, we can always consider not using the flipped edge if it's worse. So the best distance after flipping a specific edge is min( original distance (if S->T still exists without using the flipped edge) , distance using reversed edge (S -> v -> (flipped) u -> T) and also possibly other uses like multiple traversals? But in a shortest simple path, we wouldn't use the same edge twice. So the only new possibility is to use the flipped edge once in the reversed direction. Could there be a path that uses the flipped edge in its original direction after flip? No, because it's reversed. Could there be a path that uses it twice? That would be longer. So the candidate for improved distance is: dist(S, v) in the graph without the edge u->v but with v->u? Actually when we flip, the edge becomes v->u. So a path could go S -> ... -> v -> u -> ... -> T. This uses the reversed edge. So the distance would be d1(v) + 1 + d2(u), where d1(v) is the distance from S to v in the modified graph (with the flipped edge reversed), and d2(u) is the distance from u to T in the modified graph. However we cannot directly use original distances because the modified graph lacks the original direction u->v but adds v->u. This could affect d1(v) and d2(u). For d1(v), the removal of u->v might increase distance to v if the only path used that edge; but maybe there is an alternative path. For d2(u), the removal of u->v might affect distances from u to T if the original best path from u to T used that edge? Actually u->v was an outgoing edge from u; after flip, it becomes an incoming edge to u, so u loses an outgoing edge and gains an incoming edge. The distance from u to T could increase if the original shortest path from u to T used that edge. But there could be alternative paths. So d1(v) and d2(u) are not the same as original distances.
Thus we cannot simply compute with original distances. However there is a known technique for handling edge reversal in directed graphs for shortest path distances: we can compute distances from S to all nodes in the original graph (forward) and distances from all nodes to T in the original graph (reverse). Then for flipping an edge (u->v), the new distance using the reversed edge would be dist(S, v) + 1 + dist(u, T), provided that the shortest path from S to v does not use the original edge (u->v) in the original direction, and the shortest path from u to T does not use that edge either. But if they do, then those distances may not be achievable after flipping because the edge is gone. However we could consider alternative paths for those distances. But if the original shortest distances used that edge, we could try to compute alternative distances that avoid that specific edge. However those alternative distances might be longer. So the candidate distance using reversed edge might actually be larger than dist(S, v) + 1 + dist(u, T) computed from original distances. However the true distance using reversed edge would be the minimum over all paths from S to v that do NOT use the edge u->v (since it's reversed, it's not available in that direction) plus 1 plus the minimum over all paths from u to T that also do not use the edge u->v (again, not available) and also possibly not using the reversed edge? But the reversed edge is used exactly at that step, so the path from u to T cannot use the reversed edge again. However it's allowed to use the reversed edge again? That would be using the same edge twice, but shortest simple path wouldn't, but could still be considered; but we can ignore because that would be longer. So basically we need distances in a graph where the original edge u->v is removed and a new edge v->u is added. That's a single-edge change.
We could compute for each edge the new shortest path distance using BFS from S in the modified graph, but that would be O(M*(N+M)). Might be acceptable? Let's estimate: N ≤ 1000, M ≤ 10000. BFS O(N+M) ≈ 11000. M=10000 => 110 million operations. In C++ with efficient adjacency list, 110 million might be okay (under 1 sec? Probably borderline but likely okay given typical contest time limits of 2-3 sec). However the input can have multiple datasets? The problem statement didn't specify the number of datasets, but it could be up to maybe a few. The sample has one. We need to ensure we can handle worst-case multiple datasets. But maybe it's acceptable.
But wait, we have to output the distance (number of edges) and road number. BFS on unweighted graph is linear.
But we also need to consider the case where no flip yields a shorter route; we need original distance. So we must compute the original shortest path distance from S to T. That's straightforward BFS.
Now, we could do for each edge e: compute the shortest path after flipping e. But we must be careful: flipping might affect the graph globally; but we can compute BFS from S in the modified graph each time. That would involve constructing adjacency for each edge? We could start with original adjacency, then for each edge we temporarily reverse it and run BFS. But reversing one edge modifies the graph; we need to modify adjacency lists accordingly. Since M up to 10000, we could for each edge: create a copy of adjacency with the modification? That would be expensive. Better: In BFS, we can treat the edge specially: For each neighbor exploration, we need to consider that the flipped edge direction is reversed. One approach: For each edge e = (u, v), we run BFS from S, using the original graph but with that one edge's direction reversed. We can implement BFS by iterating over adjacency list of each node; but for node u, its outgoing edges normally include v; after flip, u no longer has edge to v, but v gets edge to u. So we could modify the adjacency on the fly: For each node, we can iterate over its outgoing edges, but skip the edge if it's the flipped one and its direction is original; and for node v, we add an extra outgoing edge to u. However we need to handle efficiently. Since M is not huge, we could pre-store edges list. For BFS, when we expand node x, we need to iterate over its outgoing neighbors in the modified graph. That can be done by iterating over all original outgoing edges of x, but if x == u and the edge is (u->v), we ignore it; if x == v, we add u as a neighbor (since the edge is reversed). But we must also consider that there could be multiple parallel edges: if there are multiple edges between same directed pair, flipping one of them means we remove that specific edge and add its reverse. However, the other parallel edges remain unchanged. So we need to treat edges individually. So we need to know which specific edge is flipped; its effect is only that particular edge's direction changes.
Thus BFS for a given flipped edge e = (u,v) can be done as:
- Use a visited array, queue.
- Start from S.
- For current node x:
- For each outgoing edge from x in the original graph (iterate over adjacency list of outgoing edges, each edge has target and index), we consider it as a valid outgoing edge unless (x == u and the target == v and the edge index == e). That is, if it's the specific edge we flipped, we skip it because it's no longer in that direction.
- Additionally, if x == v, we consider an extra outgoing edge to u (the reversed direction of the flipped edge). But careful: if there are other edges from v to u originally, they remain. So we add one extra neighbor u to account for the reversed edge.
- But we must ensure we don't double-count if there is already an original edge from v to u; the reversed edge adds an extra one (since it's a distinct edge). So we need to treat it as an additional edge.
Thus BFS can be performed by checking conditions.
Complexity: For each edge, BFS visits up to N nodes, and for each node we iterate over its outgoing edges. The total sum of outgoing edges over all nodes is M. So per BFS we would examine each outgoing edge from each visited node. In worst case BFS visits all nodes, and we examine all M edges each time? Actually for each node we iterate over its outgoing edges. So total operations per BFS is O(N + M) if we use adjacency list and iterate over all outgoing edges of each node visited. Since we visit at most N nodes, and each node's outgoing edges may be many, but overall each edge is considered at most once per BFS (when its source node is visited). So per BFS O(N+M) ≈ up to 11000 operations. Times M=10000 gives 110 million. That is acceptable in C++ with decent implementation. However we need to also handle memory and multiple datasets. 110 million is not huge; typically 100 million simple operations is under 1 second? Might be around 0.5-1 sec in optimized code. But we also need to consider worst-case: maybe N=1000, M=10000 for each dataset, but number of datasets could be up to maybe 10? Still okay.
But we need to also compute the original distance (no flip). That's just one BFS.
We need to output the minimal distance after flipping any edge (including possibly not flipping). But if the best distance is achieved by flipping some edge and yields distance less than original, we output that distance and the smallest index among those achieving that minimal distance. If the original distance is minimal (i.e., flipping any edge does not give a strictly smaller distance), we output original distance and 0.
But careful: There is a nuance: After flipping an edge, the distance could be the same as original. That's not strictly smaller, so we would not choose it because we output 0 only if no direction change results in a shorter route. So if the original distance is infinite (no path), but flipping some edge yields a finite path, that's definitely shorter (since infinite is not a number, but we consider infinite distance as something large). So we need to treat unreachable as distance INF (e.g., large number). Then flipping may yield finite distance, which is less than INF, so it's an improvement. So we need to compute the minimal finite distance.
Also, after flipping, the distance might become less than original. So we need to compute the best distance and which edge gives it (or none). If multiple edges give the same best distance (less than original), pick smallest index.
But we also must consider the possibility that after flipping an edge, the new distance might be the same as original but still we might want to output 0 because it's not shorter. However if original distance is INF (unreachable) and flipping yields a path, then we output that finite distance and the edge index. That's correct.
Now, we need to decide whether to consider the case of not flipping at all as a candidate for minimal distance, but we only output edge number 0 if no flip yields a shorter distance than the original. That means we compare the best distance among flips (strictly less than original) to original. If no flip gives distance < original, output original 0. However what if original distance is INF and flipping yields finite distance? Then best flip distance < INF, so we output that distance and the edge. If multiple edges give finite distances, pick the smallest distance; if ties, smallest index.
But we also need to handle the scenario where flipping an edge could produce a distance that is also INF (still unreachable). That's fine.
Implementation plan:
-
Read N; if N==0 break.
-
Read S, T.
-
Read M.
-
Store edges in arrays: from[i], to[i] for i=1..M.
-
Build adjacency list for original graph: for each node, list of (neighbor, edge_index) outgoing edges.
-
Compute original distance D0 using BFS from S to T on original graph. If unreachable, D0 = INF (some large number, say N+1 or bigger than possible maximum: max distance is at most N-1, but with flipping, it could be up to? The graph could have cycles; shortest path simple path length ≤ N-1. But if there is a path with flipped edge, it could also be at most N-1? Possibly more if graph is not simple? But shortest path simple is at most N-1. So INF can be something like 1000000.
-
Initialize best_dist = D0, best_edge = 0.
-
For each edge e from 1 to M:
- Compute distance after flipping edge e: D_e = BFS_flip(e).
- If D_e < best_dist:
best_dist = D_e; best_edge = e;
else if D_e == best_dist and e < best_edge? But we only update when strictly less. But if we get same distance as best_dist but best_edge is 0 (original) and we are considering flips that are not shorter, we shouldn't update because best_dist is D0 and best_edge=0, and if D_e == D0, it's not shorter; we don't want to change because we only care about shorter. However if D0 is INF and some flip gives finite distance, that's less, so we update. For ties when D_e == best_dist and best_edge != 0? That would mean we already found a flip that gives that distance, and maybe we found another flip giving same distance. According to problem: "If there are multiple ways to obtain the shortest distance, choose one with the smallest road number." So if multiple flips give the same best distance (which is less than original), we pick the smallest index. So if we have best_dist from a previous flip, and we encounter another flip with same distance, we should update best_edge to min(best_edge, e) only if best_dist is achieved by a flip (i.e., best_edge != 0) and D_e == best_dist. But careful: If original distance is finite and we haven't found any flip with distance less than D0, best_edge remains 0 and best_dist = D0. When we encounter a flip with distance == D0, that is not less, so we shouldn't update because we only want flips that give strictly shorter distance. So we need to treat that case: only consider flips with distance < D0 to update best_dist and best_edge. However, what if D0 is not reachable (INF) and some flip gives finite distance D_e; that D_e is < INF, so we update. Then later we might find another flip giving same D_e; we should keep the smallest index. So we need to handle updating for flips only if D_e < original D0 (if we haven't updated yet) or if we already updated and D_e == current best_dist (which is < D0) then we keep min index.
But our loop: we start best_dist = D0, best_edge = 0. For each e, compute D_e. If D_e < best_dist: set best_dist = D_e, best_edge = e. Else if D_e == best_dist and best_edge != 0: we need to set best_edge = min(best_edge, e). But note: if D_e == best_dist but best_edge == 0, that means best_dist == D0 and D_e == D0, but we shouldn't update because we only want shorter. But if D0 is INF, best_edge is 0, but INF is huge, and D_e < INF, so condition D_e < best_dist triggers. So best_edge becomes non-zero. Then later if D_e == best_dist (and best_dist < INF), we update to keep min index. So we can incorporate:
if (D_e < best_dist) {
best_dist = D_e;
best_edge = e;
} else if (D_e == best_dist && e < best_edge) {
best_edge = e;
}
But careful: if best_dist is D0 (original) and D_e == D0, then best_edge is 0, and e < best_edge is false because e >=1. So we won't update. That's correct.
Thus algorithm: BFS for each edge. Complexity O(M*(N+M)). For N=1000, M=10000, each BFS is about 11000 steps; total 110 million. That should be okay.
But we need to implement BFS efficiently: Avoid dynamic allocations per BFS. Use static arrays for visited and distance. For each BFS, we can have an array dist of size N+1 initialized to -1. Use a queue (like std::queue). For each node x, we iterate over original outgoing edges (list of (to, edge_id)). For each edge, if edge_id == e and x == from[e] and to == to[e] (i.e., it's the flipped edge in original direction), skip. After iterating original edges, if x == to[e] (i.e., the target of original edge), we consider an extra neighbor: from[e]. Because after flipping, edge is reversed, so from[e] becomes reachable from to[e]. But we must ensure that we don't double-add if there is already an edge in original from to[e] to from[e] that we already considered? We treat extra edge as a separate edge; we should add it. However careful: There might be multiple parallel edges from to[e] to from[e]; the reversed edge adds one more. So we should treat it as an extra outgoing neighbor.
But we need to be careful about the case when the flipped edge is a self-loop? From the problem: "Some roads may start and end at the same point." So edge (u,u). If we flip it, it stays (u,u) (since reversing a self-loop is the same). So flipping a self-loop doesn't change the graph. So for such edge, the BFS after flipping is same as original. So we can skip BFS for self-loop? But we can still compute, it would give D0. But that wouldn't improve.
Implementation: For each edge e, let u = from[e], v = to[e]. If u == v: flipping does nothing, so D_e = D0 (or we can skip). But we might still consider but it won't be better.
Now, BFS details:
We need to compute shortest path from S to T after flipping edge e.
We can run BFS from S, using a queue. Dist array initialized to -1. dist[S]=0; push S.
While queue not empty:
x = queue.front; queue.pop();
if x == T: we can break early? Actually we can break when we pop T? But we might have early termination. However BFS processes nodes level by level; if we find T, we can break and return dist[T]. That can speed up.
For neighbors:
-
For each original outgoing edge (x, w, id) in adj[x]:
if id == e && x == u && w == v: skip (because that edge direction is removed)
else: if dist[w] == -1: set dist[w] = dist[x]+1; push w.
-
Additionally, if we are at node x == v, then after flipping, there is an extra outgoing edge from v to u (the reversed edge). However note: There might already be an edge from v to u that we already processed in the loop above, but the reversed edge is separate. So we should add this extra neighbor: if x == v, then consider neighbor u. But careful: if the original edge is self-loop (u==v), then we already have the original edge (which is same), but flipping doesn't change. So for self-loop, we don't need extra addition because the edge remains the same. But we can handle uniformly: For self-loop, u==v. The original edge is from u to u. After flipping, it's still from u to u. So the graph unchanged. In our BFS, we would skip the original edge if it's the flipped one? Actually if we skip the original edge because we treat it as removed? That would be wrong because flipping a self-loop doesn't remove it; it stays as a self-loop. So we should not skip it. So for self-loop, we must not skip the edge. But in our rule: we skip the edge if (x == u && w == v && id == e). For self-loop, u==v, so when x==u, w==v, id==e, we would skip the edge. That would incorrectly remove the self-loop. So we need to treat self-loop specially: since flipping doesn't change direction, we should not skip it. So we should check: if u != v and x == u && w == v && id == e, then skip. If u==v, we do not skip because the edge still exists (self-loop). Similarly, the extra addition: if x == v and u != v, we add an extra edge to u. For self-loop, we shouldn't add extra because it's already present (or if we add, it's same as existing? Adding would duplicate but may cause double counting; but we can just not add for self-loop). So handle condition: if u != v and x == v, then consider neighbor u.
Alternatively, we can treat the flipped edge as: original edge u->v is removed, and a new edge v->u is added. That holds for u != v. For u == v, removal and addition cancel, so graph unchanged. So we can handle accordingly.
Thus BFS for e:
- Precompute u = from[e], v = to[e].
- If u == v: D_e = D0 (since graph unchanged). So we can skip BFS and just compare.
Otherwise:
Run BFS:
dist array fill with -1.
queue.
dist[S] = 0; push S.
while queue not empty:
x = pop.
if x == T: break (maybe after processing? we can break after we set dist[T] but before processing neighbors? Actually we can check at pop: if x == T, we have found the distance; we could break out of loop because BFS ensures first time we encounter T is minimal. However we might have set dist[T] when we pushed it. So we can break after we pop T; but careful: we might have set dist[T] when we discovered T, and we are about to pop it. So if we break after pop, we have the correct distance. Or we can break early when we first set dist[T] while processing neighbors, but that would require checking each neighbor. Simpler: after BFS, dist[T] is answer; we can early exit if we find T while processing neighbors; but BFS is not too heavy.
We need to compute neighbors as described.
One nuance: The extra edge from v to u might be already present in the original adjacency list from v to u. But we should treat it as an additional edge, not replacing. So we should include it regardless. That is fine: if there is already an original edge v->u, then we will process it in the original adjacency loop, and also we will add an extra edge from v to u. That effectively creates two edges from v to u: one original and one from the flipped edge. That's correct because the flipped edge is a distinct road. So we need to consider it as a separate edge.
But we have to be careful: The extra edge is only added if the flipped edge is reversed, meaning there is now an edge from v to u. So when at node v, we should consider that there is an additional neighbor u (if not already visited). However, what if there are multiple edges from v to u originally? The extra edge adds one more. So we need to consider it.
Implementation: For each BFS, for node x, after iterating original outgoing edges, if (x == v) then we consider neighbor u. But we should only consider it if we haven't already visited u to avoid duplicate processing, but that's fine. However we must ensure that we do not double count the edge when x == v and we already processed an original edge v->u in the loop. That's okay: the BFS will process neighbors; if we already processed u from the loop and set dist[u] maybe, then when we consider the extra neighbor, if dist[u] != -1, we skip. But we must be careful about distance: The extra edge may offer a shorter path to u than the original one. However BFS processes nodes in order of distance; if we discover u through the extra edge and its distance is smaller than through some other edge, we need to consider that. Since we are iterating neighbors, we will evaluate both possibilities. If u is discovered first via original edge with some distance d, then later via extra edge we see u again but dist[u] already set, we ignore. That's fine; the BFS ensures that the first time we set dist[u] is the shortest distance from S to u. Since both edges have the same cost (1), whichever discovers first yields correct distance. So adding extra neighbor is fine.
But there is one more nuance: The reversed edge v->u should be considered only if the flipped edge is not the same as any original edge? But as said, it's distinct.
Now, what about the fact that the original edge u->v is removed? In the original adjacency loop, we skip that specific edge when x == u and neighbor == v and id == e. This ensures that we don't traverse that edge. But note: there could be multiple edges from u to v; only the specific edge e is removed; others remain. So our condition must check id == e, not just u->v. So we skip only that specific edge.
Now BFS per edge seems straightforward.
Potential optimization: Since we have up to 10000 edges, each BFS might allocate a queue and distance array. We can reuse distance array by resetting to -1 each BFS, but resetting an array of size 1000 for each BFS would be 1000*10000 = 10 million, which is fine. But we need to be careful to not use memset each BFS (costly but okay). But we can also use a visited timestamp technique: maintain an array vis[N+1] with timestamps, and an integer cur_time. That could be faster. But not necessary.
However, there may be a more efficient approach using BFS from S and from T on original graph, then for each edge compute distance using reversed edge with potential alternative distances that avoid using that edge. This is typical for "shortest path with one edge reversed" problems. I recall a known technique: we compute distances from S (d1) and distances to T (d2) in original graph. Then for each edge (u,v), the candidate using reversed edge is d1(v) + 1 + d2(u), provided that the path from S to v does not use edge (u,v) and the path from u to T does not use edge (u,v). But as noted, we need to consider alternative routes if the shortest path uses that edge. However, we can compute second best distances or something like that. But perhaps we can compute distances from S to all nodes in the graph without using a specific edge? That would be heavy. However, there is a known technique for directed graphs where we can compute the effect of reversing an edge on the shortest path by considering the edge's impact on the shortest path tree. Since N is only 1000, maybe O(M*(N+M)) is okay.
But let's check worst-case: M=10000, N=1000, BFS O(N+M)=11000. 10000*11000 = 110 million. Each BFS involves loops over adjacency for each node visited. In C++, that should be fine. However, we also have to read input and output. Should pass.
But we must also consider the possibility that the graph is dense: M up to 10000, N up to 1000, so average degree ~10, not dense. So BFS per edge is about 1000 nodes visited, each node has ~10 outgoing edges -> about 10k operations per BFS, total 100 million. That's fine.
Thus we can implement straightforwardly.
Edge Cases:
-
S and T same? Problem says S != T.
-
Multiple edges: need to treat indices.
-
Graph may have no path from S to T originally; D0 = INF.
-
Flipping an edge might create a path.
-
The flipped edge might be part of a cycle etc.
-
The BFS after flip might also be infinite (no path), we treat as INF.
We'll define INF as a large number like 1e9.
Now, we need to careful about BFS implementation: Use vector<vector<pair<int,int>>> adj (1-indexed). For each node, store list of (neighbor, edge_id). Also maybe store reverse adjacency? Not needed.
Now, for each edge e: if u==v, skip BFS and set D_e = D0.
Otherwise:
- Create dist array (vector dist(N+1, -1)).
- queue q.
- dist[S] = 0; q.push(S);
- while (!q.empty()) {
int x = q.front(); q.pop();
if (x == T) break; // optional, can break because distances to T is found; but if we break, we may not have processed all nodes, but we don't need further.
// process outgoing
for (auto &p : adj[x]) {
int y = p.first;
int id = p.second;
if (id == e && x == u && y == v) continue; // skip original direction of flipped edge
if (dist[y] == -1) {
dist[y] = dist[x] + 1;
q.push(y);
}
}
// extra edge from v to u
if (x == v) {
// reversed edge
if (dist[u] == -1) {
dist[u] = dist[x] + 1;
q.push(u);
}
}
}
- D_e = dist[T] == -1 ? INF : dist[T];
But note: The extra edge from v to u is only added once, representing the flipped edge. However, consider if the flipped edge is a self-loop (u==v) we already skip.
Now, does this BFS correctly account for the removal of the original edge? Yes, we skip it. Does it correctly add the reversed edge? Yes, when x == v we consider an extra neighbor u.
One nuance: The reversed edge could also be used multiple times? BFS won't revisit nodes already visited, so it's fine.
Potential bug: The extra edge might be considered even if the original edge had multiple parallel edges? For the flipped edge, we only add one extra edge. That's correct.
Now, about early break: When we pop T, we could break the BFS loop. But we must ensure that we have already processed its neighbors? Not needed because we already have distance to T. So we can break.
Now, performance: For each BFS, we iterate over adjacency list of each visited node. If we break early when we reach T, we might not visit all nodes, which is beneficial.
Now, we need to compute original distance D0 as well. BFS from S on original graph.
Original BFS: similar but no modifications.
Now, after loop, we have best_dist and best_edge. We output best_dist and best_edge. But note: If best_edge remains 0, we output best_dist and 0. However, if original graph has no path (D0 = INF) and we also have no flip that yields a path, best_dist remains INF, and best_edge 0. Then we should output something? The problem statement probably expects a distance (maybe 0?) But what does it mean? If there is no path even after flipping any edge, then the shortest distance is infinite? But the problem likely expects to output some number? The problem says "print the shortest distance (counted by the number of passed roads) and the road number whose direction should be altered." It doesn't say that there always exists a path. If no direction change results in a shorter route, we print 0 as the road number. But if there is no route at all originally, and flipping also doesn't create a route, then the shortest distance is presumably infinite? But maybe it's guaranteed that there is always a path? Not necessarily. The problem statement doesn't guarantee existence of path. But they might expect that there is always a path after flipping? Not necessarily. In case of no path, the distance is not defined. However, typical contest problems might assume that there is at least one path after some flipping? Let's think.
If no path exists at all even after flipping any edge, then the "shortest distance" would be something like "impossible"? But they ask to print distance and road number. Possibly they ensure that there is always at least one path? The problem statement doesn't explicitly guarantee it. But we must handle the case where there is no path: what should we output? The distance could be considered as 0? But that wouldn't make sense.
We need to examine sample: Only one dataset where path exists.
Check problem statement: "If no direction change results in a shorter route, print 0 as the road number." It doesn't address the case where no route exists at all. But typical output: we print the distance (maybe a large number?) But likely there is always a route either original or after flipping because S and T are distinct and graph might be strongly connected? Not guaranteed. But we could reason: If no route exists originally, then the original distance is infinite. Flipping an edge might create a route. If no flip creates a route, then the shortest distance remains infinite. But we cannot output infinite. However perhaps the problem constraints ensure that there is always a path after some flip? I'm not sure.
Let's re-read: "Andrew R. Klein resides in the city of Yanwoe, and goes to his working place in this city every weekday." That implies there is some route maybe originally, but he is annoyed with traffic, so he wants to make it shorter. It doesn't say there is no route originally. But the possibility of no route is allowed by input? Possibly yes. But the output specification: "print the shortest distance (counted by the number of passed roads) and the road number whose direction should be altered." If there is no route at all, the shortest distance would be something like "0"? Or they might expect to print something like "0 0"? But the problem says "If no direction change results in a shorter route, print 0 as the road number." That only talks about the case when there is a route originally (since shorter route implies there is a route). It doesn't specify what to do if there is no route originally. However, in that case, any flip that creates a route would be considered shorter (since no route is like infinite). So we should output that distance and the road number. If no flip creates a route, then there is no route at all; what should we output? Perhaps "0 0"? But the distance 0 would be incorrect because route length must be at least 1 if there is a path? Could be "0" distance meaning S=T? But S != T.
Maybe the input ensures that there is always a path? The problem might be from some contest where they guarantee that S and T are connected (maybe after flipping). But not explicitly. We'll check typical tasks: "Change the direction of one road to make the route shorter" implies there is a route originally, but they didn't state it. However the problem statement says: "He has been totally annoyed with the road traffic of this city. All the roads in this city are one-way, so he has to drive a longer way than he thinks he need." That suggests there is a route, but it's longer than necessary (maybe the direct route is blocked). So original route exists. I think it's safe to assume that there is always a path from S to T in the original graph? Not necessarily, but maybe it's typical. However to be safe, we should handle the case of no path by treating distance as INF and then if no flip yields a path, then best_dist remains INF. But what to output? The problem likely expects a finite distance. But maybe it's guaranteed that there is always a path after at most one flip? Consider graph with N nodes, S and T distinct; if there is no path originally, maybe flipping some edge can create a path? Not guaranteed.
Given the problem's style, I think it's safe to assume there is at least one path originally. Because otherwise Andrew would not be able to go to work every weekday. So we can assume original graph has a path from S to T. But still, I'll implement handling of INF and if best_dist remains INF, we would output something? Maybe we can output "0 0"? But the problem says print the shortest distance and the road number. So maybe it's guaranteed that there is a route. I'll check the sample: original distance from 1 to 4 in the sample: edges: 1->2,2->3,3->4,4->1. The original shortest path from 1 to 4 is 1->2->3->4 length 3. Flipping edge 4->1 gives edge 1->4. Then path 1->4 length 1. Output: "1 4". So original distance is 3, after flip distance 1. So they output the shortest distance after flip (1) and the flipped edge index (4). So they output the new distance, not the original distance.
Thus if no flip yields a shorter route, they output original distance and 0. So original distance exists.
Thus we can assume that there is always a path from S to T in original graph. But I'm not 100% sure; but for safety, I will still handle INF case: If D0 == INF, then best_dist initially INF, best_edge = 0. Then for each flip, we compute D_e; if D_e < best_dist (i.e., finite), update. After loop, if best_dist == INF, then there is no path at all; but what to output? Could output "0 0"? The problem likely not test such case. To be robust, we could output "0 0"? But not defined. Maybe output "0 0"? However, I'll assume it's not needed.
Now, we must also consider that the BFS per edge might be somewhat heavy if we allocate vectors each time. We can optimize by reusing a global distance array and using BFS with queue and a marker array with timestamps to avoid resetting the entire array each time. That's more efficient.
We'll implement BFS_flip(e) function that uses global arrays dist and visited flag with a global timestamp. For each BFS, we increment a counter bfs_id, and have an array vis[N+1] storing the bfs_id when visited. This avoids resetting dist values for all nodes.
Pseudo:
int dist[N+1]; // but we don't need distance array? Actually BFS needs distance. We can also store distance in a separate array d[N+1] and also use vis[N+1] to indicate visited. We can use d[N+1] and a timestamp for visited: for each node, store last_bfs_id[node] indicating which BFS it was visited in. Initialize last_bfs_id to 0. For each BFS, use cur_id = ++global_counter. When we set distance for node, also set last_bfs_id[node] = cur_id. Then to check if visited, we compare last_bfs_id[node] == cur_id. This is faster than resetting array.
We'll implement BFS that returns distance.
But we also need to early exit when T is found. We'll use a queue.
Now, we also need original BFS for D0. Could also use same method.
Implementation details:
-
Use 1-indexing for nodes.
-
Store edges: from[M+1], to[M+1].
-
Build adjacency: vector<vector<pair<int,int>>> adj(N+1); for i in 1..M: adj[from[i]].push_back({to[i], i}).
-
For original BFS: we can run BFS_original() that just computes distance from S to T.
Now, for each edge e:
if (from[e] == to[e]) D_e = D0; else D_e = BFS_flip(e).
Now BFS_flip(e):
-
static int vis[N+1]; (global, maybe vector vis(N+1, 0));
-
static int dist[N+1]; (but we can combine with vis by using distance array and timestamp)
-
static int cur_bfs = 0; // timestamp
-
cur_bfs++;
-
queue q;
-
set vis[S] = cur_bfs; dist[S] = 0; q.push(S);
-
while (!q.empty()) {
int x = q.front(); q.pop();
int d = dist[x];
if (x == T) return d; // found
// process outgoing edges
for (auto &p : adj[x]) {
int y = p.first;
int id = p.second;
if (id == e && x == from[e] && y == to[e]) continue; // skip this edge
if (vis[y] != cur_bfs) {
vis[y] = cur_bfs;
dist[y] = d+1;
q.push(y);
}
}
// extra edge: if x == to[e] and from[e] != to[e]
if (x == to[e]) {
int y = from[e];
if (vis[y] != cur_bfs) {
vis[y] = cur_bfs;
dist[y] = d+1;
q.push(y);
}
}
}
-
return INF; // not reached
Make sure to use INF large enough.
But note: The BFS_flip(e) uses dist array; but we need dist per node for the current BFS. Since we use vis to check visited and dist array is overwritten for visited nodes, it's fine.
We must be careful that we are using global arrays dist and vis. But we call BFS_flip multiple times, and we reuse dist array. Since we set dist only when we set vis, it's safe.
Now, about the early return: We return d when x == T. That's the distance from S to T. Good.
Now, we must also consider that the BFS might find T through the reversed edge? That's handled.
Now, complexity: For each BFS, we iterate adjacency for each node visited. Each edge (u->v) may be examined multiple times. But total operations per BFS: sum of out-degrees of visited nodes. Since we break early when T found, we may not visit all nodes. That's beneficial.
Now, we need to consider that there might be a path that uses the reversed edge multiple times? Unlikely, but BFS handles it.
Now, potential bug: In the extra edge addition, we need to ensure that we don't inadvertently add the reversed edge when the original edge is a self-loop. We already condition: if (x == to[e] && from[e] != to[e]). So fine.
Now, about the skipping: For edge e, we skip only if id == e and x == from[e] and y == to[e]. That's correct.
Now, about memory: adjacency list stores M pairs. That's fine.
Now, we need to output best_dist and best_edge. If best_edge == 0, output best_dist and 0. But best_dist must be the distance after best flip or original. However we need to be careful: original distance D0 might be INF? But we assume not.
But what if the original graph has a path but after flipping some edge, the distance becomes shorter, but maybe the best distance is still D0? Then best_edge remains 0. Output D0 0. That's correct.
Now, consider the scenario where flipping an edge yields a distance equal to D0 but not shorter. Then best_edge remains 0. That matches problem.
Now, we must ensure that the BFS for each edge is correct. Let's test on sample:
N=4, S=1, T=4. Edges: 1->2 (1), 2->3 (2), 3->4 (3), 4->1 (4). Original BFS: dist[4] = 3. D0=3.
Now test edge 4 (4->1). BFS_flip(4): u=4,v=1. BFS from 1:
Start: dist[1]=0. Pop 1. Outgoing edges: from 1: (2,1) (skip? not e). So neighbor 2 visited dist=1. Also extra edge? x==v? v=1, x==1? x==v? yes because x=1 and v=1? Actually v=1? Wait edge 4 is (4,1) so u=4, v=1. So v=1. At x=1, we have extra edge if x==v (1==1) and u!=v (4!=1). So we add neighbor u=4. So from 1 we also have neighbor 4 via reversed edge. So we set dist[4]=1 (if not visited). So we discover T=4 at distance 1. BFS returns 1. That's correct.
Now, for other edges, flipping doesn't improve as much? For edge 1: (1,2). Flip to (2,1). BFS: Start from 1. Outgoing: original edge 1->2 is skipped, so from 1 we only have extra if x==v? v=2, not at start. So 1 has no outgoing? Actually we also have edge? 1 has only edge 1->2 (original) which is skipped. So no outgoing from 1? But we also have extra edge? x=1 != v (2), so no. So only neighbor from BFS is perhaps from extra when we visit other nodes? But we start at 1, we cannot go anywhere because the only edge from 1 is removed and no extra added at 1. So we might not reach T? Let's simulate: dist[1]=0. Pop 1. Outgoing: skip (1,2). Extra: none. So queue becomes empty. So T not reached, distance INF. So D_e = INF. That's > D0, so not chosen.
Edge 2: (2,3). Flip to (3,2). Original graph: from 1 we can go 1->2. At node 2: original edge 2->3 is removed. But there may be other edges? No. So path: 1->2 (dist1). At 2, outgoing edges: none? Actually 2 only has edge 2->3 originally. So after removal, from 2 no outgoing. But we also have extra if x == v? v=3, so when we later get to 3 we can go back to 2? But we never get to 3 because we can't reach 3. So BFS may get stuck. So D_e INF. Not better.
Edge 3: (3,4). Flip to (4,3). Original: 1->2->3. At 3, edge 3->4 removed. So from 3, after removal, no outgoing? Actually 3 only had edge 3->4. So cannot go to 4. But we have extra edge from v=4 to u=3 when we get to 4, but we cannot reach 4. So unreachable. So INF.
Thus only edge 4 gives 1, which is less than 3, so best_dist=1, best_edge=4. Output "1 4". Good.
Now, we must ensure that we handle the case where the reversed edge may create a shorter path but also removal of the original edge might affect the path to v or from u. Our BFS accounts for that.
Now, we need to consider if there are multiple edges with same u,v? For edge e, skipping only that specific edge ensures that parallel edges remain. Our BFS does that.
Now, potential optimization: We could precompute BFS from S in original and BFS from T on reversed graph, and then compute for each edge some candidate distances using the concept of "shortest path avoiding edge" but we already decided simple BFS per edge is fine.
But we must be mindful of time. Let's compute more precisely: N up to 1000, M up to 10000. BFS per edge O(N+M). 10000 * 11000 = 110e6 operations. In C++, each operation is a few instructions; should be okay within 2 seconds. However, if there are multiple datasets, say up to 10, it could be 1.1e9 operations, which might be too much. But typical contest problems limit number of datasets such that total input size is manageable. Since input ends with 0, we don't know number of datasets. But with N=1000, M=10000, each dataset has about 10,000 edges, which is relatively large. Possibly only one dataset per test. I'd still go with this approach.
But there might be a more efficient solution using BFS trees and computing distances from S and to T for each edge removal, but it's more complex.
One more nuance: The BFS for each edge could be optimized by precomputing distances from S to all nodes and from all nodes to T, and then for each edge, compute candidate distance using reversed edge but also considering if the original shortest path uses that edge, we need to use alternative paths. However, we could compute for each node the distances from S (dS) and distances to T (dT) on original graph. Then, for each edge (u,v), the candidate distance using reversed edge is: if we can get from S to v without using this edge, and from u to T without using this edge, then we can have path S->...->v->u->...->T using reversed edge. But we need to know distances without using that specific edge. We can compute second-best distances or compute distances from S to all nodes without using that edge? That's per edge again.
But maybe we can compute the set of edges that lie on all shortest paths? Not needed.
Given constraints, BFS per edge is acceptable.
However, we need to be careful about memory and recursion depth. BFS uses queue.
Implementation steps:
- Read N.
- While N != 0:
- Read S, T.
- Read M.
- Initialize vectors: from, to (size M+1).
- adj.clear(); adj.resize(N+1).
- For i=1..M:
read a, b.
from[i]=a; to[i]=b;
adj[a].push_back({b,i});
- Compute D0 using BFS_original.
- Set best_dist = D0; best_edge = 0.
- For e=1..M:
if from[e] == to[e]: D_e = D0; // self-loop, no change
else:
int d = bfs_flip(e);
if (d < best_dist) {
best_dist = d; best_edge = e;
} else if (d == best_dist && best_edge != 0 && e < best_edge) {
best_edge = e; // but note: if best_edge is 0 and d == best_dist (which equals D0), we shouldn't update. The condition best_edge !=0 ensures we don't update if best_edge is 0 because that indicates original is best and d == D0, not an improvement.
}
// Actually we need to also handle case where D0 is INF and d is also INF? Then d < best_dist false, and best_edge stays 0. That's fine.
- Print best_dist and best_edge.
But we must be careful: The condition for updating when d == best_dist and best_edge !=0 ensures we pick smallest index among flips that achieve the same best distance (which is less than D0). However, consider scenario: D0=5, we find edge e1 with d=4, set best_dist=4, best_edge=1. Later we find edge e2 with d=4 and e2<e1? Actually e2>e1 maybe, we compare if d == best_dist and e < best_edge, then update. But we need to update only if best_edge !=0 (which is true after first flip). Good.
But what if D0=5, we find edge e1 with d=5 (equal to D0). That does not trigger d < best