We need to parse the problem. Given an undirected weighted graph of N nodes (stations) and k edges (railway lines). For a test case, we are given A, B, C. The person wants to go from A to C via B. That is, the path must go from A to B and then from B to C. However, they want to go as early as possible, i.e., shortest total travel time (distance). So essentially, we need to find the shortest path from A to B plus shortest path from B to C. But note: the path might not be simple? Actually, the person wants to go from A to C via B, meaning he will first travel from A to B, then from B to C. He can take the shortest routes for each leg independently, and the combined path is A -> (shortest path to B) -> B -> (shortest path to C) -> C. However, the combined path might have repeated edges or nodes, but that's allowed? Typically, traveling from A to B then B to C, the overall route is concatenation of two shortest paths. There is no requirement to avoid revisiting nodes or edges. But note: if the two shortest paths share some edges or nodes, it's still a valid route. The problem says "if it exists" meaning if there is a path from A to B and from B to C. So we need to output the total distance (sum of distances of shortest A-B and shortest B-C) and the actual path to be covered by train, i.e., the sequence of stations visited along the entire journey from A to C via B. However, we need to output the path as a single list of station sids. The path should be the concatenated path: the shortest path from A to B, then the shortest path from B to C. But careful: if we simply concatenate, we'll have B repeated (once at the end of first path, once at the start of second path). The overall path from A to C via B should visit B only once? Typically, when traveling from A to C via B, you go from A to B, then from B to C, so the route includes B as a point of change, but the train might pass through B without stopping? The problem says "path to be covered by train". It doesn't specify that you have to list stations without duplicates; likely you should list the full sequence of stations visited along the way. If the shortest path from A to B is a sequence: A = v0, v1, ..., vk = B. And from B to C: B = u0, u1, ..., um = C. The full journey would be: v0, v1, ..., vk, u1, u2, ..., um (since B is already included, we don't duplicate it). So the path output should be A ... B ... C with B appearing only once at the transition. So we need to output the concatenation without duplicate B.
Thus, the solution: For each test case, compute shortest paths from A, from B, from C? Actually we need: shortest A->B path and shortest B->C path. We can compute distances and predecessor information from A to all nodes, and from B to all nodes, and maybe from C? But to reconstruct path from B to C, we need predecessor from B to C. We can compute Dijkstra from source B to get distances to all nodes and also store parent pointers for the shortest path tree (or DAG). However, note that there might be multiple shortest paths. The problem statement: "path to be covered by train if it exists". Which path do we output? The problem says "What you have to do is to print the total distance and path to be covered by train if it exists". It doesn't specify that if there are multiple shortest paths, we choose any? Usually they want the path that corresponds to the concatenated shortest paths. But if there are multiple shortest paths from A to B, any yields the same distance. The same for B to C. But we need to output some specific path. Probably any shortest path is acceptable, but we need to be consistent. Often such problems require us to output the path (the sequence of nodes) that is lexicographically smallest or something? Not specified. So we can choose any shortest path. We'll reconstruct using parent pointers from Dijkstra where ties are broken arbitrarily (but we need deterministic output). Since input constraints up to 100k nodes and 100k edges, and T up to 100, we need efficient algorithm. But note total T up to 100, but N and k each up to 100k, so worst-case sum over test cases could be 10 million nodes and edges? Actually worst-case if each test case max, T=100, total N up to 10 million, total edges up to 10 million, which might be okay if we use efficient implementation? But usually in problems, T is small and N, k are large. But we need to handle up to 100 test cases of size 100k each, total 10M nodes and 10M edges, which might be borderline but okay in C++ with fast I/O and Dijkstra using heap. However, we also need to reconstruct paths, which requires storing parent arrays for two runs (A and B). That's O(N) per test case. So overall memory ~ O(N). But N up to 100k per test case, so okay.
But we need to be careful: The graph is undirected weighted edges with positive weights (d up to 10^7). So Dijkstra works.
Edge count k up to 100k. So adjacency list representation.
Now special case: If there is no path from A to B or from B to C, then output "No Train Found.".
Otherwise, total distance = dist_A[B] + dist_B[C].
Then we need to output the path: first the path from A to B (sequence of nodes), then the path from B to C but skipping the first node (B) because it's already included. So we need to construct the path list.
We have to store parent from A and from B. For Dijkstra, we store parent that we used to reach each node on the shortest path. Typically we store when relaxing: if dist[v] > dist[u] + w, then parent[v] = u; if equal, we might need to choose a specific parent to get a particular path. Since the path is not specified, we can just pick the first one (i.e., the one that comes from the relaxation order). But to avoid complications, we can store parent arbitrarily for ties. That should be fine.
But careful: Dijkstra from A gives a shortest path tree (or forest). For any node that has a shortest path from A, we can trace parent pointers back to A. Similarly from B. However, if there are multiple shortest paths, the parent we store during Dijkstra may produce some path. It should be fine because the distance is correct and any shortest path is acceptable.
But consider that the concatenated path might have cycles? Not important.
Now about output format: For each test case, if path exists, first line: total distance (presumably integer? d can be up to 10^7, sum up to 2*10^7, fits in int? But with many edges, could be larger? Actually, distance sum could be up to (N-1)*10^7 ~ 1e12 if N=100k, d=10^7, but shortest path could be up to that. So need 64-bit. Use long long.
Then second line: path: sequence of station sids separated by spaces. The sample output shows "6 3 5 1 8 2" for second test case. That is the path for A=6, B=3, C=2? Actually input: "6 3 2" meaning A=6, B=3, C=2. Output total distance 692 and path "6 3 5 1 8 2". Let's check: That path goes 6->3 (so direct? Edge? The graph edges: see edges given: 3 5 55, 3 6 179, ... There is edge 3-6 weight 179. So from 6 to 3 direct edge weight 179? Actually there is edge: "3 6 179". So shortest from 6 to 3 could be direct with 179. But the path they output includes 6->3 (so that's the leg from A=6 to B=3). Then from 3 to 2, they gave: 3->5->1->8->2. That seems to be a path from 3 to 2. Let's see if that is the shortest? Possibly. So the concatenated path: 6 (A) -> 3 (B) -> 5 -> 1 -> 8 -> 2 (C). That matches the expected output. So they combined them without repeating B.
Thus algorithm: Dijkstra from A, get distA, parentA. Dijkstra from B, get distB, parentB. Check if distA[B] != INF and distB[C] != INF. If either is INF, print "No Train Found." Else compute totalDist = distA[B] + distB[C]. Then reconstruct path1 = list from A to B using parentA (going from B backwards to A, then reverse). Path2 = list from B to C using parentB, but starting from C backwards to B, then reverse, then drop the first element (B). Then combine path1 + path2. Output totalDist and combined path.
Now about path reconstruction: parent arrays store predecessor for each node on the shortest path from source. For source itself, parent[source] = -1 (or 0). For Dijkstra, we initialize parent[source] = -1. Then when relaxing, if we update distance, set parent[v] = u. If there is a tie (equal distance), we may or may not update. It doesn't matter.
Now complexities: For each test case, we run Dijkstra twice. With N up to 100k, k up to 100k, Dijkstra using binary heap (priority_queue) is O((N + k) log N). That's fine.
But we need to be careful with large input: T up to 100, but in practice the sum of N and k across test cases might be high but still manageable if we use fast I/O and clear structures for each test case.
Potential issues: The graph might have multiple edges? Possibly not mentioned, but we can handle by storing adjacency list with duplicates. That's fine.
Edge weights up to 10 million, but distance sum could be large: use long long.
Now we need to output path as space-separated integers. The path length could be up to N (worst-case), but that's okay.
Now sample input: first test case: N=6,k=6 edges, then A=1,B=3,C=6? Actually input says: "1 3 6". So A=1,B=3,C=6. Output "No Train Found." Let's check: Possibly no path from A to B or B to C? Let's see graph: edges: 1-2(2),2-5(5),2-3(4),1-4(1),4-3(3),3-5(1). So there is path from 1 to 3: via 1-4-3 (1+3=4) or 1-2-3 (2+4=6) so exists. From 3 to 6: but station 6 is not in edges? Actually N=6, so node 6 exists but no edges connecting it? Looking at edges: none involve node 6. So indeed no path from 3 to 6. So output No Train Found.
Now second test case: N=10, edges 10, then A=6,B=3,C=2. Output distance 692 and path "6 3 5 1 8 2". Let's verify: distA[6] from source 6? Actually we need dist from A=6 to B=3. Compute from graph. Graph edges:
1 5 78
1 8 221
2 7 92
2 8 159
3 5 55
3 6 179
3 10 237
4 8 205
5 6 191
8 10 157
We can compute shortest 6->3: direct edge 179 (6-3 weight 179). Alternative: 6-5 (191) +5-3(55)=246 >179. So shortest =179. So distA[B]=179.
Now distB[C] i.e., from B=3 to C=2: compute shortest from 3 to 2. Options: 3-5-1-? Actually check connections: 3 connected to 5 (55),6(179),10(237). 2 connected to 7(92),8(159). So need path from 3 to 2. Possibilities: 3-5 (55), 5-1 (78), 1-8 (221), 8-2 (159) => total 55+78+221+159=513? That's 513. Alternative: 3-5 (55),5-6 (191),6? no. 3-10 (237),10-8(157),8-2(159)=553. 3-5-1-8-2 =55+78+221+159=513. 3-5-6? not helpful. Also 3-6-5-1-8-2 =179+191+78+221+159=828. So shortest seems 513. But the output distance is 692. Wait total distance is 692, so distA[B]+distB[C]=179+distB[C]=692 => distB[C]=513. That matches our computed 513. So indeed they got distB[C]=513 and the path they gave for leg B->C is 3->5->1->8->2? That's 3-5 (55) + 5-1 (78) + 1-8 (221) + 8-2 (159) = 513. Yes. So path from 6 to 3: direct 6-3 (179). Then from 3 to 2: 3-5-1-8-2. Combined: 6 3 5 1 8 2. So matches.
Thus algorithm is correct.
Now we must implement.
Potential pitfalls: Input might be large, so use fast I/O (scanf/printf in C++, or cin with sync off). Use adjacency list: vector of vector<pair<int, long long>> or store as vector.
We need to store parent arrays: vector parA(N+1), parB(N+1). Also distances: vector distA(N+1, INF), distB similarly.
Dijkstra function: (source, vector& dist, vector& parent). We'll use a min-heap of pair<long long, int> (distance, node). Initialize dist[source]=0, parent[source]=-1 (or 0). Push (0, source). While heap not empty, pop. If popped distance > dist[node], continue. Then iterate over adjacency list of node: for each neighbor (v, w): if dist[v] > dist[node] + w, update dist[v] = dist[node] + w, parent[v] = node, push (dist[v], v). If equal, maybe we do nothing, because we don't need to update parent. But sometimes we might want to record some parent for path reconstruction if there are multiple equally shortest paths. The problem doesn't specify which path to output, so it's fine.
But careful: If we later reconstruct path from B to C using parentB, we need that parentB[C] is set correctly such that there is a chain back to B. This works because Dijkstra ensures that for each node v, parent[v] is the predecessor that gave the shortest distance when we first updated it or later if we update. Since we update only when strictly smaller, there might be cases where a node is first reached with a suboptimal distance, later a better distance comes and we update parent. That's fine. The final parent pointers will form a tree that yields shortest paths.
But if there are ties (multiple shortest paths with same distance), we only set parent when we find a strictly better distance. So for nodes that have equal distances via different parents, we will keep the parent from the first time we set the distance (maybe from the first path). But that distance is final, and it's a shortest path. So it's okay.
One nuance: For source, we set parent[source] = -1. When reconstructing path from source to target, we can traverse from target back to source using parent until -1, then reverse.
Now about memory: For each test case we allocate adjacency list of size N+1. Since T can be up to 100, but we can deallocate after each test case by using local vectors that go out of scope.
Now about output: print total distance as integer (probably without decimal) and path.
Now check constraints: d up to 10,000,000, N up to 100,000, so distances can be up to 1e12, use long long (64-bit). Use INF = 1e18.
Now complexity: O(T * ( (N+k) log N )). In worst-case T=100, N=100k, k=100k => 100 * 200k log 100k ~ 100 * 200k * 17 ~ 340 million operations, which might be a bit high but could still pass in C++ if optimized. But typical problem sets have T small or N sum limited. However we need to ensure efficient implementation: use fast heap (std::priority_queue with std::greater) and adjacency list using vector. Use scanf/printf. Possibly the problem expects solution using Dijkstra but with early exit? Not necessary.
But we can also run Dijkstra only from A and B? Actually we need distances from A to B and from B to C. We could run Dijkstra from A and from B. That's two runs. That is okay.
Alternatively, we could compute single-source from B and from A. That's what we do.
Now we need to be careful about path reconstruction: from B to C using parentB. However, parentB gives the predecessor on the path from B to C? Actually parentB is built from B as source. So from B to C, the path is B -> ... -> C. To reconstruct, we start from C, follow parentB back to B, then reverse, we get the sequence from B to C. That's correct.
Now combine: path1 (A to B) and then path2 (B to C but without the first element B). However, careful: If the path from B to C is just B->C (i.e., direct edge), then path2 after removing first element would be just C. So combined path: path1 (includes B at the end) + [C]. That's fine.
If path1 is just A->B (i.e., A and B are same? But A,B,C distinct? Not necessarily, they could be same? Problem doesn't specify they are distinct. But if A == B or B == C, we need to handle. Let's consider: The person wants to go from A to C via B. If A == B, then the journey is just from B to C? Actually "via B" means he wants to go through B. If A == B, he starts at B, then goes to C. The total distance is distB[C] (since distA[B]=0). Path would be: from A to B is just A (i.e., B), and then from B to C. The concatenated path would be A (=B) followed by path from B to C (without duplicate B) => just the path from B to C. That's fine. Similarly if B == C, then path from A to B, then from B to C is zero distance for second leg, path would be just A->B. So we need to handle. Also if A == B == C? Then distance 0, path just A. But the problem might not have such cases. But we should handle gracefully.
Our algorithm with parent arrays: For Dijkstra from A, if A==B, then distA[B]=0, and parentA[B] = -1? Actually parentA[B] = parentA[A] = -1. When reconstructing path from A to B, we need to get list of nodes from A to B. If A==B, the path should be just [A]. So our reconstruction: start at B, follow parent until source A (i.e., until node == -1). But if A==B, we start at B which is A, and parent[B] = -1, so the loop would produce no nodes? We need to treat source specially: we can push B into list, then while parent[current] != -1, current = parent[current]. But that would give list: start with B, then while parent[current] != -1, add parent. For A==B, we have current = A, parent[A] = -1, so we add A to list, then exit. Then we reverse. Actually better: we can collect nodes by starting at target and adding target, then moving to parent until we reach source (or until parent is -1). But we need to know when to stop: we want to stop when we reach source (A). So we can do: vector path; for (int v = target; v != source; v = parent[v]) { path.push_back(v); } then after loop, push source. Then reverse. For A==B, target == source, the loop condition v != source fails immediately, so we push nothing, then push source, then reverse gives [A]. That's correct. So we need to store source id. So for reconstruction, we need source and target.
Thus:
vector get_path(int source, int target, const vector& parent) {
vector path;
for (int v = target; v != source; v = parent[v]) {
path.push_back(v);
}
path.push_back(source);
reverse(path.begin(), path.end());
return path;
}
But note: parent[source] should be something like -1 or self; we need to ensure that the loop terminates, i.e., there is a chain from target to source. This assumes that parent is correctly set for all nodes on the path.
Now we combine: vector pathAB = get_path(A, B, parentA); // gives A...B
vector pathBC = get_path(B, C, parentB); // gives B...C
Then final path = pathAB concatenated with pathBC starting from index 1 (skip first element B). But if B==C, then pathBC will be just [B]. Then we need to skip the first element (B) from pathBC, but then we would be left empty, so final path = pathAB. That's correct. If A==B, pathAB = [A] (since A==B). pathBC = [B...C]. Removing first element of pathBC yields the rest (which could be just [C] if B==C? Actually if A==B and B!=C, pathBC = [B, ..., C]; remove first gives [..., C]; combine: [A] + [..., C] = [A, ..., C] which is correct (A is B). If B==C and A!=B, pathAB = [A,..., B]; pathBC = [B]; remove first gives empty; final path = pathAB, which is A...B, correct. If A==B==C, pathAB=[A], pathBC=[A]; remove first from pathBC gives empty; final path = [A]; total distance = 0. This works.
Now we need to compute distances: We'll run Dijkstra for each source.
Implementation details:
- Use 1-indexed nodes.
- For each test case, read N, k.
- Build adjacency list: vector<vector<pair<int, long long>>> adj(N+1);
- For i from 1 to k: read a,b,d. Add both directions: adj[a].push_back({b,d}); adj[b].push_back({a,d});
- Then read A,B,C.
- Run Dijkstra(A, distA, parentA).
- If distA[B] == INF: print No Train Found. Continue to next test.
- Else run Dijkstra(B, distB, parentB).
- If distB[C] == INF: print No Train Found.
- Else compute total = distA[B] + distB[C]; print total.
- Reconstruct paths: pathAB = get_path(A, B, parentA); pathBC = get_path(B, C, parentB);
- Combine: final_path = pathAB; final_path.insert(final_path.end(), pathBC.begin()+1, pathBC.end());
- Print final_path: for i, print node; space-separated, newline.
Now need to consider memory: parent arrays of size N+1 int. Dist arrays of size N+1 long long. That's fine.
Now about Dijkstra implementation with priority_queue: Use typedef pair<long long,int> PII; Use greater for min-heap: priority_queue<PII, vector, greater> pq; or use negative distances.
We must clear adjacency list and arrays for each test case.
Now we need to handle T up to 100, but sum of N may be up to 10^7? Actually if each test case is max 100k, total 10 million nodes and edges, which is manageable in memory if we reallocate per test case. But 10 million nodes with adjacency lists and vectors could be heavy but maybe okay. Typically in such problems, the sum of N over test cases is limited. But we should still optimize.
Alternative approach: Since we need only distances from A to B and B to C, we could run Dijkstra from B only, then from A only, which we already do.
One more nuance: If A and B are same, then Dijkstra from A (i.e., source B) will set distA[B]=0; path reconstruction yields just A. Good.
Now about output format: The sample output shows "No Train Found." (including period). Exactly that.
Now let's test with sample: Works.
Now consider large input: Use fast reading: scanf.
Now check path reconstruction: get_path uses parent array. Ensure parent[source] is set to -1 or 0? We'll set parent[source] = -1. In Dijkstra, we init dist[source]=0, parent[source]=-1, push (0, source). Then when we relax, we set parent[v] = u.
Now in get_path, we iterate for v = target; v != source; v = parent[v]. But if parent[v] is -1 and source is not -1, this may break if we attempt to go from some node that is not reachable? But we only call get_path when dist is finite, so path exists, so the chain will end at source eventually. Also, if source == target, the loop condition fails immediately, we push source, okay.
Now confirm that parent chain is correct: In Dijkstra, when we update dist[v] with a new smaller distance, we set parent[v] = u. This ensures that there is a path from source to v via u. Since we only update when dist decreases, the final parent pointers form a tree rooted at source (or forest). For any node v with finite dist, following parent repeatedly leads to source because each step reduces the distance (since parent is closer to source) and eventually reaches source. That's valid.
Now what about ties? Suppose there is an equal distance path later; we don't update parent, so the parent pointer remains from first discovered path. That's fine.
Now we have to be careful about integer overflow: use long long for distances.
Now implement.
Time complexity might be high, but we can also try to early exit Dijkstra once we have found the target? In Dijkstra, once we pop the target node from the priority queue, we can break because distances are finalized. That can save time, especially if we only need distance to one node. However we also need parent pointers to reconstruct path, but that is already set when we relax. So we can break when we pop target from PQ. But we also need parent pointers to reconstruct path. That's fine. But careful: For Dijkstra from A, we need distance to B and parent chain from A to B. If we break when B is popped, we have finalized dist[B] and parent[B] is set. The parent chain may rely on some nodes that are not yet popped? Actually Dijkstra ensures that when we pop a node, its distance is finalized. So parent[B] is final. However, the parent chain might involve nodes that haven't been popped? Actually they would have been popped earlier if they are on the shortest path? For parent[B] = u, u would have been popped before B because dist[u] < dist[B] (since edge weight positive), so u is popped earlier. So it's fine. Breaking early can significantly speed up when the graph is large and B is close to A. Similarly for Dijkstra from B to C.
Thus we can modify Dijkstra to accept a target node and stop when it is popped. The function signature: void dijkstra(int source, vector& dist, vector& parent, int target = -1). If target != -1, we can break when we pop target. If target == -1 (i.e., all nodes), we continue. We'll use target for A->B and B->C. That will improve.
One more optimization: Use adjacency list with vector<pair<int, long long>>, but we can store w as int? d up to 1e7 fits in int, but distances may sum up to long long. So store w as int or long long? We can store as long long to avoid casts, but memory wise pair<int, long long> is 16 bytes maybe. Could also store as pair<int,int> and cast to long long when summing. I'll store as pair<int, long long>.
Now about reading: use scanf("%d %d %lld", &a, &b, &d). d is int? Actually d up to 10^7 fits in int, but we'll read as int and assign to long long.
Now we need to handle potential multiple test cases: reinitialize vectors each test case. We'll declare adjacency list inside loop.
Now check for potential overflow in sum of distances: up to maybe 1e12, so printf with %lld.
Now output path: print each node separated by space, with newline after.
Now code skeleton:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
void dijkstra(int src, int n, const vector<vector<pair<int,ll>>>& adj, vector& dist, vector& parent, int target = -1) {
fill(dist.begin(), dist.end(), INF);
fill(parent.begin(), parent.end(), -1);
dist[src] = 0;
priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<pair<ll,int>>> pq;
pq.push({0, src});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue;
if (u == target) break; // found target
for (auto& edge : adj[u]) {
int v = edge.first;
ll w = edge.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
parent[v] = u;
pq.push({dist[v], v});
}
}
}
}
vector get_path(int src, int tgt, const vector& parent) {
vector path;
for (int v = tgt; v != src; v = parent[v]) {
path.push_back(v);
}
path.push_back(src);
reverse(path.begin(), path.end());
return path;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, k;
scanf("%d %d", &N, &k);
vector<vector<pair<int,ll>>> adj(N+1);
for (int i = 0; i < k; ++i) {
int a, b; ll d;
scanf("%d %d %lld", &a, &b, &d);
adj[a].push_back({b, d});
adj[b].push_back({a, d});
}
int A, B, C;
scanf("%d %d %d", &A, &B, &C);
vector distA(N+1);
vector parentA(N+1);
dijkstra(A, N, adj, distA, parentA, B);
if (distA[B] == INF) {
printf("No Train Found.\n");
continue;
}
vector distB(N+1);
vector parentB(N+1);
dijkstra(B, N, adj, distB, parentB, C);
if (distB[C] == INF) {
printf("No Train Found.\n");
continue;
}
ll total = distA[B] + distB[C];
printf("%lld\n", total);
vector pathAB = get_path(A, B, parentA);
vector pathBC = get_path(B, C, parentB);
// combine
for (size_t i = 0; i < pathAB.size(); ++i) {
printf("%d", pathAB[i]);
if (i+1 < pathAB.size() || pathBC.size() > 1) printf(" ");
}
for (size_t i = 1; i < pathBC.size(); ++i) {
printf("%d", pathBC[i]);
if (i+1 < pathBC.size()) printf(" ");
}
printf("\n");
}
return 0;
}
But careful: printing spaces might be tricky. We can collect all nodes in a vector and print with loop. That's simpler.
vector full_path = pathAB;
full_path.insert(full_path.end(), pathBC.begin()+1, pathBC.end());
for (size_t i = 0; i < full_path.size(); ++i) {
if (i > 0) printf(" ");
printf("%d", full_path[i]);
}
printf("\n");
That works.
Now note: The path may be large (up to N). Using vector insertion is O(N) which is fine.
Now we need to test with sample.
Let's simulate with sample:
First test case: N=6,k=6, edges, A=1,B=3,C=6. Dijkstra from A to B (target=3) will compute dist[3]=4? Actually shortest 1-4-3 =4. So distA[B] = 4 (finite). Then Dijkstra from B to C (target=6) will find no path, so distB[C]=INF, thus print No Train Found. OK.
Second test case: N=10,k=10, edges, A=6,B=3,C=2. Dijkstra from 6 to target 3: Should find dist=179, path 6->3 (since direct). Parent for 3: 6. PathAB: get_path(6,3) => start v=3, while v!=6: path push 3, then v=parent[3]=6? Actually careful: get_path as implemented: for(v=tgt; v!=src; v=parent[v]) path.push_back(v). So for tgt=3, src=6: v=3, v!=6 true, push 3, then v=parent[3]=6. Next iteration: v=6, condition v!=src? 6!=6 false, exit loop. Then push src (6). Then reverse => [6,3]. That's correct (order 6,3). PathBC: get_path(3,2). Need parent chain from B=3 to C=2. Dijkstra from B=3 to target=2. Should compute shortest path: 3->5->1->8->2 with total 513. Parent chain: For 2, parent is 8; 8 parent maybe 1; 1 parent 5; 5 parent 3. So get_path: start v=2, push 2, then v=parent[2]=8; push 8, v=parent[8]=1; push 1, v=parent[1]=5; push 5, v=parent[5]=3; v=3, condition v!=src? (src=3) 3!=3 false, exit loop; push src (3); reverse => [3,5,1,8,2]. Combined: pathAB = [6,3]; pathBC without first => [5,1,8,2]; full = [6,3,5,1,8,2]. Output matches sample.
Great.
Now consider possible edge cases: If there are multiple shortest paths, we output one. The problem likely accepts any. However, in some judges, they may compare output exactly; if there are multiple possible paths, they might require a specific path. We need to confirm: The problem statement does not specify which path to output when multiple exist. Typically in such problems, any correct path is accepted, but some judges require the path that is lexicographically smallest or something. But the sample doesn't hint at that. However, we should check typical problems: IRCTC? Might be from some contest. Usually they accept any valid shortest path. But to be safe, we can adopt a deterministic rule: when distances are equal, choose the parent that gives lexicographically smallest path? Not specified. It's safer to output the path we get from Dijkstra with standard relaxation (which depends on adjacency order). Since adjacency order is the order of input edges, it could be arbitrary. But we can enforce a consistent tie-breaking to increase chances of matching expected output. In sample, the chosen path for B->C is 3->5->1->8->2. Could there be another shortest path with same distance? Possibly 3->5->6? Not same. Check: 3->5->6? 3-5=55, 5-6=191 => 246, too high. 3->10->8->2: 237+157+159=553. So only one path of distance 513? Actually maybe 3->5->6? No. So no tie. So not a problem.
But there might be ties. For example, if there are two equal shortest distances, Dijkstra may pick the one based on order of processing edges. This may differ from expected. Usually, judges for problems like these accept any path as long as distance matches. But sometimes they require the path that is "as per the order of station sids" maybe smallest sids? Not mentioned. I'll check problem statement: "print the total distance and path to be covered by train if it exists". No further specification. So likely any path is fine.
However, we need to note: The path we output must be a valid path with the exact distance we computed. Since we compute shortest distances, it's fine.
Now we need to ensure the parent pointers produce a valid path from source to target. When we break early upon popping target, we might not have relaxed all edges from nodes that are still in heap. But that's fine because we only need the shortest path to target. However, when we break early, the parent pointer for target is already set. But what about nodes that are not yet processed? Not needed.
But careful: If we break when we pop target, we have finalized distance to target. However, there may be other nodes whose distances are not final, but we don't need them. So it's fine.
Now some implementation details:
-
We'll pass target to dijkstra; if target == -1 (or 0), we don't break; but we know targets for each run: for A->B target is B; for B->C target is C. But we also need parent array for reconstruction of path from B to C. So we set target = C for the second run.
-
In Dijkstra, after we break, we might still need parent of target set; it is. So good.
Now about memory: For each test case, we create adjacency list and distance/parent arrays. They are destroyed after loop.
Now about reading: We'll use scanf and printf.
Now potential pitfalls: The input format: first line T, then each test case: N k, then k lines of a b d, then line with A B C. In sample, they have spaces between numbers. Good.
Now what about the case where there is no path from A to B or B to C? Output exactly "No Train Found." including period and capital letters. The sample shows "No Train Found." So exactly that.
Now check for trailing spaces: The path output should be numbers separated by spaces, no trailing space. Using the loop with if(i>0) add space before each element except first solves that.
Now we need to ensure we use long long for distances. In Dijkstra, we need to compare dist[v] > dist[u] + w. w is long long. Use INF = 1e18 (greater than max possible: N * max_d = 1e5 * 1e7 = 1e12, so 1e18 safe).
Now code.
But let's double-check constraints: N up to 100000, k up to 100000, t up to 100. So total edges across test cases up to 10 million. That's a lot, but maybe fine. However, Dijkstra's complexity O((N+K) log N). For 100 test cases each with 100k nodes and edges, that's 100 * (200k * log(100k)) ~ 100 * 200k * 17 = 340 million operations, plus overhead. Might be borderline but could pass if optimized. However, we break early when target found, which reduces average case. Also many test cases may be smaller. I think it's okay.
But we can also run Dijkstra from A only once? Actually we need A->B and B->C. Could run from A and B only. That's two runs. Could also run multi-source? Not needed.
We should also consider using an efficient heap: std::priority_queue is fine. Use vector for adjacency. Use reserve if needed.
We should also consider the possibility that the graph is disconnected: then no path.
Now let's think about potential issues: The problem states "If a railway line connects station A to B with distance d than it means it will also connects station B to station A with same distance d." So undirected.
Now about output: For the second test case, the output is "692" on one line and "6 3 5 1 8 2" on next line. Our code prints total distance, newline, then path, newline. That matches.
Now check for case where A==B==C: distA[B]=0, distB[C]=0, total=0. Path: get_path(A,B) => [A], get_path(B,C) => [B], combine => [A] (since pathBC after skip first becomes empty). So we print 0 and then "A". That seems plausible. But is this allowed? Probably.
Now edge case: If A==C != B? Then path: A->B->A? That might be allowed? The person wants to go from A to C via B; if A==C, then they go from A to B and back to A. That's possible. Our algorithm works.
Now about memory: vector of pairs for adjacency: each edge stored twice. For k=100k, that's 200k entries, each pair is two ints? Actually pair<int,long long> may be 16 bytes (assuming 8-byte long long, 4-byte int + padding). So 200k16 = 3.2MB per test case, plus other arrays: dist (two arrays of long long: 100k8=0.8MB each, total ~1.6MB, parent arrays two: 100k*4=0.4MB each, total 0.8MB). So per test case maybe ~6-8MB, times 100 would be 800MB if all allocated simultaneously, but they are deallocated after each test case, so peak memory is about 8MB, which is fine.
Now we need to ensure we clear vectors properly between test cases.
Now about time: We'll implement Dijkstra as:
void dijkstra(int src, int n, const vector<vector<pair<int,ll>>>& adj, vector& dist, vector& parent, int target) {
fill(dist.begin(), dist.end(), INF);
fill(parent.begin(), parent.end(), -1);
dist[src] = 0;
priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<pair<ll,int>>> pq;
pq.emplace(0, src);
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d != dist[u]) continue;
if (target != -1 && u == target) break;
for (const auto& [v, w] : adj[u]) {
ll nd = d + w;
if (nd < dist[v]) {
dist[v] = nd;
parent[v] = u;
pq.emplace(nd, v);
}
}
}
}
We'll use target = -1 to indicate no early break. But we pass B and C accordingly.
Now potential bug: When we break early, we might not have relaxed all neighbors of u? But we break after popping u, and we already processed its edges. If we break before processing neighbors? Actually we break after popping, before processing neighbors? In code above, we check if u == target after popping and before processing neighbors? Actually the check is after popping, before processing edges. If we break at that point, we won't process its edges, but that's fine because we already have the shortest distance to target, and we don't need further updates. But we need the parent of target already set? It is set when we updated dist[target] to its final value. That happens when some node u that is predecessor of target relaxes it. That node must have been popped earlier, and it would have processed its edges and updated target. So by the time we pop target, its distance is final and parent is set. So we can break immediately. So checking before processing edges is okay.
But we must ensure that we pop target only when its distance is finalized. That's true.
Now we must also consider if target is the source itself. Then dist[src]=0, parent[src]=-1. When we start, we push (0,src) and then pop it. At that moment, u=src, and if src==target (i.e., A==B), then we break. That is fine: we break before processing edges? Actually if we break before processing edges, we might not have updated distances for other nodes, but we only need distance to target (which is 0) and parent of target (which is -1). So it's fine.
So Dijkstra with early break works.
Now implement get_path. However, get_path requires that the parent chain from target to source is correctly set. For source == target, parent[source] is -1, but our loop condition v != src; so it will skip loop, then push src, good.
Now one more nuance: In Dijkstra, we initialize parent array with -1. For source, we set parent[src] = -1. For other nodes, when we set dist[v] we set parent[v] = u. So chain is good.
Now we need to ensure that the get_path function uses source and target correctly. In pathAB, source = A, target = B. In pathBC, source = B, target = C.
Now potential edge: if the path length is huge (N up to 100k), the recursion in get_path (iterative) is fine.
Now one more optimization: We might not need to run Dijkstra from A and B separately if we compute distances from B to all and from B to all? Actually we need distA[B] and distB[C] and also paths. So two runs.
Now we also need to note that we might compute Dijkstra from B twice? Actually we run from A to get path A->B, and from B to get path B->C. That's fine.
Now we should test with a simple case.
Test 1:
1
3 2
1 2 1
2 3 1
1 2 3
A=1,B=2,C=3. DistA[2]=1, DistB[3]=1, total=2. PathAB: 1 2. PathBC: 2 3. Combined: 1 2 3. Output: "2\n1 2 3". Works.
Test 2:
1
3 0 (k=0, but N>=3 so k could be 0? Actually constraints say k>=1? No, it says 1 ≤ k ≤ 100000, so k at least 1. But if there is no edge, it's invalid per constraints? Not necessarily, it says 1 ≤ k, so k>=1. So at least one edge. But anyway we can handle k=0, but not needed.
Now about T=100, we need to reset structures. Our code does that.
Now consider if there is a path but the distance sum may exceed 32-bit. So use %lld.
Now we need to include necessary headers: <bits/stdc++.h> is fine.
Now let's think about possible pitfalls: The problem might have large input and output, so we must use fast I/O. Use scanf/printf.
Now about reading long long: d is up to 1e7, fits in int, but we can read as int and assign to long long. However, we might have to store as long long for distances anyway. So reading with %d and casting is fine, but to avoid confusion, use %lld for d as well? But d is within int, but we can read as long long to be safe. The input spec says "three numbers a, b and d", d is distance, likely integer. So we can read with %lld. I'll use scanf("%d %d %lld", &a, &b, &d) with d as long long. That's fine.
Now about printing: Use printf("%lld\n", total). For path, print each integer.
Now ensure newline after each test case's output.
Now complexity: Dijkstra with early break.
Potential improvement: Use adjacency list as vector of vector<pair<int, int>> where weight stored as int to reduce memory and improve cache. But then distance calculations need long long, but we can cast. Let's do that: store w as int (since d <= 1e7). So adjacency: vector<vector<pair<int, int>>> adj(N+1). Then in Dijkstra, we compute nd = dist[u] + w (w is int, dist[u] is long long). That's fine.
I'll change to int for w.
Now code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
void dijkstra(int src, int n, const vector<vector<pair<int,int>>>& adj, vector& dist, vector& parent, int target) {
fill(dist.begin(), dist.end(), INF);
fill(parent.begin(), parent.end(), -1);
dist[src] = 0;
priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<pair<ll,int>>> pq;
pq.push({0, src});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d != dist[u]) continue;
if (u == target) break;
for (auto& [v, w] : adj[u]) {
ll nd = d + w;
if (nd < dist[v]) {
dist[v] = nd;
parent[v] = u;
pq.push({nd, v});
}
}
}
}
vector get_path(int src, int tgt, const vector& parent) {
vector path;
for (int v = tgt; v != src; v = parent[v]) {
path.push_back(v);
}
path.push_back(src);
reverse(path.begin(), path.end());
return path;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, k;
scanf("%d %d", &N, &k);
vector<vector<pair<int,int>>> adj(N+1);
for (int i = 0; i < k; ++i) {
int a, b, d;
scanf("%d %d %d", &a, &b, &d);
adj[a].push_back({b, d});
adj[b].push_back({a, d});
}
int A, B, C;
scanf("%d %d %d", &A, &B, &C);
vector distA(N+1);
vector parentA(N+1);
dijkstra(A, N, adj, distA, parentA, B);
if (distA[B] == INF) {
printf("No Train Found.\n");
continue;
}
vector distB(N+1);
vector parentB(N+1);
dijkstra(B, N, adj, distB, parentB, C);
if (distB[C] == INF) {
printf("No Train Found.\n");
continue;
}
ll total = distA[B] + distB[C];
printf("%lld\n", total);
vector pathAB = get_path(A, B, parentA);
vector pathBC = get_path(B, C, parentB);
vector full_path = pathAB;
full_path.insert(full_path.end(), pathBC.begin()+1, pathBC.end());
for (size_t i = 0; i < full_path.size(); ++i) {
if (i > 0) printf(" ");
printf("%d", full_path[i]);
}
printf("\n");
}
return 0;
}
Now we need to ensure that the adjacency list uses int for weight, but Dijkstra's nd = d + w: w is int, d is long long, nd is long long. That's fine.
Potential bug: Using "auto& [v, w]" in range-based for loop: This is C++17 feature, acceptable in most judges. We can also use "const auto& edge" and then v = edge.first, w = edge.second. I'll keep C++17.
Now test with sample input.
Let's simulate quickly:
Input:
2
6 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
1 3 6
10 10
1 5 78
1 8 221
2 7 92
2 8 159
3 5 55
3 6 179
3 10 237
4 8 205
5 6 191
8 10 157
6 3 2
Our code:
First test: dijkstra from A=1 to B=3.
Adjacency:
1: (2,2), (4,1)
2: (1,2), (5,5), (3,4)
3: (2,4), (4,3), (5,1)
4: (1,1), (3,3)
5: (2,5), (3,1)
6: none? Actually N=6 but node 6 has no edges.
Dijkstra from 1: initial dist[1]=0.
PQ: (0,1). Pop 1, process edges: to 2: nd=2 -> update dist[2]=2, parent[2]=1; push (2,2). to 4: nd=1 -> update dist[4]=1, parent[4]=1; push (1,4). PQ: (1,4), (2,2). Pop 4 (dist=1). Process edges: to 1 (dist[1]=0, no update), to 3: nd=1+3=4, update dist[3]=4, parent[3]=4; push (4,3). PQ: (2,2), (4,3). Pop 2 (dist=2). Process edges: to 1 (0+2=2 no), to 5: 2+5=7, update dist[5]=7, parent[5]=2; push (7,5); to 3: 2+4=6, dist[3] currently 4, no update. PQ: (4,3), (7,5). Pop 3 (dist=4). u == target (3)? Yes, break. So distA[3]=4, parentA[3]=4, parentA[4]=1. Path from 1 to 3: 1-4-3. Good.
Now dijkstra from B=3 to C=6: target 6.
Adjacency: node 6 has no edges, so unreachable. Dijkstra will process nodes, but never set dist[6] finite. So distB[6] = INF. Print No Train Found. matches.
Second test: N=10, edges as above. dijkstra from A=6 to B=3:
Adjacency:
6: (3,179), (5,191)
3: (5,55), (6,179), (10,237)
others.
Dijkstra from 6: dist[6]=0.
PQ: (0,6). Pop 6, process edges: to 3: nd=179, update dist[3]=179, parent[3]=6; push (179,3). to 5: nd=191, update dist[5]=191, parent[5]=6; push (191,5). PQ: (179,3), (191,5). Pop 3: u == target (3) -> break. So distA[3]=179, parentA[3]=6. Good.
Now dijkstra from B=3 to C=2: target 2.
Initialize dist[3]=0.
PQ: (0,3). Pop 3, process edges: to 5: nd=55, update dist[5]=55, parent[5]=3; push (55,5). to 6: nd=179, update dist[6]=179, parent[6]=3; push (179,6). to 10: nd=237, update dist[10]=237, parent[10]=3; push (237,10). PQ: (55,5), (179,6), (237,10). Pop 5 (dist=55). Process edges from 5: edges: from adjacency list: 5: (1,78), (3,55), (6,191). So:
- to 1: nd=55+78=133, update dist[1]=133, parent[1]=5; push (133,1).
- to 3: nd=55+55=110, dist[3]=0, no.
- to 6: nd=55+191=246, dist[6]=179, no.
PQ now: (133,1), (179,6), (237,10). Pop 1 (dist=133). Process edges from 1: edges: (5,78), (8,221).
- to 5: nd=133+78=211, dist[5]=55, no.
- to 8: nd=133+221=354, update dist[8]=354, parent[8]=1; push (354,8).
PQ: (179,6), (237,10), (354,8). Pop 6 (dist=179). Process edges: (3,179), (5,191).
- to 3: nd=179+179=358, no.
- to 5: nd=179+191=370, no.
PQ: (237,10), (354,8). Pop 10 (dist=237). Process edges: (3,237), (8,157).
- to 3: nd=474, no.
- to 8: nd=237+157=394, which is less than current dist[8]=354? Actually 394 > 354, so no.
PQ: (354,8). Pop 8 (dist=354). Process edges: (1,221), (2,159), (4,205), (10,157).
- to 1: nd=354+221=575, no.
- to 2: nd=354+159=513, update dist[2]=513, parent[2]=8; push (513,2).
- to 4: nd=354+205=559, update dist[4]=559, parent[4]=8; push (559,4).
- to 10: nd=354+157=511, which is less than dist[10]=237? No 511>237.
Now PQ contains (513,2), (559,4). Pop 2: u == target (2) -> break. So distB[2]=513, parent[2]=8, parent[8]=1, parent[1]=5, parent[5]=3. Path: 3->5->1->8->2. So get_path(B=3, C=2) yields [3,5,1,8,2]. Good.