We need to solve the problem: given undirected graph with weighted edges (positive? w>=1). For each special vertex among k specials, we need the maximum distance (as defined: distance = min over all paths of the maximum edge weight along the path, i.e., the minimax path, also known as the minimum bottleneck path) to any other special vertex. Then output that distance for each special.
We need to answer for each special vertex: farthest distance to another special, where distance is the minimum bottleneck (minimize max edge weight) between two vertices.
Observation: The distance defined is exactly the "bottleneck" distance; it is also known that in an undirected graph, the minimum bottleneck path between two vertices is given by the minimum over all paths of the maximum edge weight. This is like the minimax path. There is known connection to minimum spanning tree (MST): The unique path between two vertices in the MST has the property that its maximum edge weight is equal to the minimax distance between those vertices. Actually, for any two vertices, the minimum possible maximum edge weight over a path connecting them is equal to the maximum edge weight on the unique path between them in any minimum spanning tree (or more generally in any minimum bottleneck spanning tree). This is a known property: MST minimizes the maximum edge weight among spanning trees, and the path in the MST between two vertices has the minimum possible maximum edge weight. So we can reduce the problem to a tree (any MST). Then distances between vertices become the maximum edge weight along the tree path.
Thus we can: build an MST (or any minimum bottleneck spanning tree) of the graph. Since m up to 1e5, n up to 1e5, we can build MST using Kruskal sort edges by weight. Then we have a tree (or forest; graph is connected so tree). The special vertices form a subset of nodes.
Now the problem becomes: Given a tree with weighted edges, and a set of special nodes (k of them). For each special node, we need the maximum over other special nodes of the maximum edge weight along the tree path between them. This is essentially, for each special node, the farthest special node in terms of the "path bottleneck" which equals the max edge weight on the path. However, note that the distance function is not additive but is determined by the maximum edge along the path. So we need to compute for each special node, the maximum "bottleneck distance" to any other special node.
We need to compute an array ans[x_i] for each special.
We have a tree with n nodes, edges have weights. We need to answer: for each node in the set S (specials), what is the maximum bottleneck distance to any node in S? Actually, to any other special node? The problem says: "For each special vertex, find another special vertex which is farthest from it (i.e., the corresponding distance is maximum possible) and output the distance between them." So we need the max distance to any other special vertex. So if there is only one special? but k>=2, so at least 2 specials. So we need farthest among others.
In tree, the bottleneck distance d(u,v) = max edge weight on path between u and v. For a fixed u, we want max_{v in S, v≠u} d(u,v).
This is reminiscent of computing "diameter" under this metric? But we need per node.
Observation: Since the distance is defined by the maximum edge on the path, the farthest distance from u is determined by the maximum over all special nodes v of the max edge weight along path. This is like: consider the tree, and we are interested in the maximum edge weight encountered when traveling from u to any special node.
We can think of the tree as having edge weights, and we want for each special node, the furthest special node under the "max on path" metric. This is analogous to "bottleneck distance" which satisfies ultrametric? Actually, the max edge weight along a path defines a metric? It satisfies triangle inequality: d(u,w) ≤ max(d(u,v), d(v,w)). Indeed, because the path from u to w can be broken, the maximum edge weight on the u-w path is at most max of maxima on u-v and v-w subpaths. Actually, it's exactly: d(u,w) ≤ max(d(u,v), d(v,w)). Because any edge on u-w path is either on u-v or v-w segment. This is the strong triangle inequality, making it an ultrametric if also symmetric and d(u,v)=0 iff u=v. So it's an ultrametric? Indeed, the minimum bottleneck distance is an ultrametric if the graph is a tree? Wait, in a tree, d(u,v) = max edge weight along unique path. This satisfies the ultrametric inequality: d(u,w) ≤ max(d(u,v), d(v,w)). Because the max on u-w path is the max of the union of edges on u-v and v-w paths, which is max of those two maxima. So yes, it's an ultrametric on the set of nodes. For any triple, the two largest distances are equal (ultrametric property). Actually, ultrametric means that for any three points, the two largest distances are equal. This property holds if the tree is a 'minimum spanning tree' and the metric is defined by the bottleneck? Not exactly, but I think the bottleneck distance on a tree satisfies the property: for any three nodes u,v,w, among d(u,v), d(v,w), d(u,w), the largest two are equal. Let's test: In a tree, suppose the three nodes, the unique paths; the maximum edge weight on each path. The bottleneck distance corresponds to the weight of the highest edge on the path. For three nodes, the highest edge among all edges involved; the distances are essentially the weight of the highest edge on each pair's path. It may hold that the two largest are equal because they are all determined by the heaviest edge in the union? Actually, consider a line: nodes a-b (weight 1), b-c (weight 2). Then distances: d(a,b)=1, d(b,c)=2, d(a,c)=2. Largest two: 2 and 2, equal. Consider more complex: a star with center o, edges weights: a-o:3, b-o:2, c-o:1. Distances: d(a,b)=max(3,2)=3, d(a,c)=max(3,1)=3, d(b,c)=max(2,1)=2. Largest two: 3 and 3, equal. So indeed it holds: for any tree with edge weights, the bottleneck distance is an ultrametric? Let's try a tree with three leaves where internal edge weight heavy: Suppose tree: leaf1 - x (w=5), x - y (w=10), y - leaf2 (w=3), y - leaf3 (w=4). Distances: leaf1-leaf2 = max(5,10,3)=10, leaf1-leaf3 = max(5,10,4)=10, leaf2-leaf3 = max(3,4)=4. Largest two: 10 and 10, equal. So seems property holds: For any three nodes, consider the three paths; the maximum edge weight among the three paths, the two pairs that go through that maximum edge will have distance equal to that maximum, and the third pair might be smaller. So indeed the two largest distances are equal. Therefore, the distance metric is an ultrametric. In an ultrametric, the farthest distance from any point to any other point in a set is the same for all points, unless the set is not "complete"? Actually, consider a finite set S in an ultrametric space. The diameter (max distance between any two points) is D. For any point x in S, the maximum distance from x to any other point in S is D, unless x is the unique farthest? Wait, in an ultrametric, the set of distances from a point to others might not all be equal to D, but the maximum might be D. Could there be a point whose farthest neighbor distance is less than the global diameter? For example, consider three points with distances: A-B=5, A-C=5, B-C=3. The diameter is 5. For point B, the farthest distance is max(5,3)=5? Actually B's distances: to A=5, to C=3, so farthest is 5. For point C, farthest is 5. So all points have farthest =5. Consider four points forming a "balanced" tree? In an ultrametric, the distances form a hierarchical clustering. For any point, the farthest other point is always the diameter of the whole set? I think so: In an ultrametric, take any point x. The maximum distance from x to any other point is max_{y} d(x,y). Consider the diameter D = max_{u,v} d(u,v). I suspect that for any x, max_{y} d(x,y) = D. Because let u,v be a pair achieving D. For any x, by ultrametric property, among d(u,v), d(x,u), d(x,v), the two largest are equal. Since d(u,v)=D is the largest (or at least among them), then either d(x,u)=D or d(x,v)=D (or both). Actually, consider the triple (u,v,x). Since d(u,v)=D is the maximum among the three distances? Possibly there could be a distance larger? D is maximum overall, so d(u,v) ≥ d(x,u) and d(u,v) ≥ d(x,v). So d(u,v) is the largest of the three. The ultrametric inequality implies that the two largest are equal. Since d(u,v) is the largest, the second largest must equal d(u,v). But the second largest could be either d(x,u) or d(x,v). That means that at least one of d(x,u) or d(x,v) must equal d(u,v). Therefore, for any x, there exists either u or v such that d(x, that point)=D. So indeed, the farthest distance from any point is exactly the global diameter. Wait, check: if D is the global maximum distance, pick pair (a,b) achieving D. For any x, either d(x,a)=D or d(x,b)=D. So yes, each point has at least one of a or b at distance D. So the maximum distance from any point to another point in S is at least D, but it cannot exceed D, so it's exactly D. Therefore, for all points in the set, the farthest special vertex distance is the same: the diameter of the set under the bottleneck metric.
But is that true? Let's verify with a simple counterexample? Consider a set of three special nodes arranged on a line with edge weights: a--b (1), b--c (2). Then distances: a-b=1, a-c=2, b-c=2. Diameter =2. For a, farthest = max(1,2)=2. For b, farthest = max(1,2)=2. For c, farthest = max(2,2)=2. OK.
Consider a more complex tree with specials not containing the pair that achieves the maximum? But the maximum is defined over all pairs in S. So indeed there is a pair achieving D. For any other x, either d(x,a)=D or d(x,b)=D. So yes, that seems to hold. But wait: The ultrametric inequality states: For any three points x,y,z, d(x,z) ≤ max(d(x,y), d(y,z)). This does not guarantee that the two largest are equal; that's a stronger property that holds for ultrametrics. But does bottleneck distance on a tree actually satisfy that stronger property? Let's check: In a tree, d(u,v) = max edge weight on the path. Consider three nodes u,v,w. Let w_max be the maximum edge weight among all edges in the union of paths. Suppose the heaviest edge e* with weight W is on the path between u and v. Then d(u,v)=W. Now what about d(u,w) and d(v,w)? The path u-w may or may not include e*. If e* lies on u-w path, then d(u,w)≥W, but since W is maximum among all edges, d(u,w) cannot exceed W? Actually there might be heavier edges on u-w path? But W is the maximum among all edges in the union, so any edge on u-w path has weight ≤ W, but if e* is on u-w, then the max is exactly W. If e* is not on u-w, then the max on u-w is ≤ something less than W. Similarly for v-w. Since e* is on the u-v path, but not necessarily on the others. Could it happen that neither u-w nor v-w contain e*? For e* to be on u-v but not on u-w, that would mean w is on the same side of e* as u? Actually consider tree: e* is an edge that separates the tree into two components. Suppose u is in component A, v in component B. e* connects A and B. For any node w, if w is in A, then the path u-w stays in A, so does not cross e*, but v-w goes from B to A crossing e*, so includes e*. If w is in B, then u-w includes e* and v-w does not. So exactly one of u-w or v-w includes e*. Thus one of d(u,w) and d(v,w) will be at least W, and since W is the maximum possible, it is exactly W. So we have: one of d(u,w) or d(v,w) equals W, and the other might be ≤ W. So for any w, among the three distances, the two largest are both equal to W? Let's sort: if d(u,v)=W, d(u,w) may be < W or =W (if w is in B), d(v,w) similarly. Suppose w in A: then d(u,w) ≤ something less than W, d(v,w)=W. So distances: W (u,v), W (v,w), and something ≤ W (u,w). So the two largest are both W. If w in B: d(u,w)=W, d(v,w) ≤ W, again two largest are W. If w is exactly on e*? but it's a vertex, not edge. So indeed, for any three nodes, the two largest distances are equal. So it is an ultrametric.
Thus, we have the property: For any finite set S in this ultrametric, all points have the same farthest neighbor distance: the diameter of S. So the answer for each special vertex should be the same number, the diameter (maximum bottleneck distance between any two special vertices). Let's test with the provided examples:
Example 1: n=2, edges weights: (1,2,3), (1,2,2), (2,2,1) (self-loop). The MST? Since graph is small, consider two vertices. The minimax distance between 1 and 2: you can choose the edge of weight 2, so distance = 2. The farthest for each special (both specials) is 2, matches.
Example 2: Provided output: 3 3 3. So indeed all three specials have answer 3. And they note: distance between 1-2=3, 1-3=3, 2-3=2. So diameter is 3, and for vertex 2, farthest is max(3,2)=3, so matches.
Thus, the answer for all special vertices is the same: the maximum distance (bottleneck) between any two special vertices.
But wait: is this always true? Consider if the set S is such that the maximum distance is achieved by a pair (a,b). For any other special c, we need to show that either d(c,a)=D or d(c,b)=D. As argued, due to ultrametric property on trees, it holds. But is the bottleneck distance on the original graph exactly equal to the bottleneck distance on any MST? Yes, because the MST path gives exactly the minimax distance. However, we must ensure that the minimax distance is indeed an ultrametric on the set of all vertices (or at least on S). The property we derived depends on the tree structure; but the original distance is defined on the graph, and it's equal to the tree distance on the MST for all pairs. So it is indeed an ultrametric because the MST distances satisfy it. So yes.
Therefore, the problem reduces to: Given a connected undirected graph with weighted edges, and a set S of special vertices, compute the maximum minimax distance between any two special vertices. Then output that number for each special vertex.
So we just need to compute the diameter of the set S under the bottleneck metric. Which equals the maximum over all pairs of specials of the minimum bottleneck path cost. That is exactly the maximum edge weight on the path between them in the MST, but we can also compute without explicitly building the tree? But building MST is easy.
Thus the solution: Compute MST of the graph (Kruskal), get a tree. Then for the set of special vertices, we need to find the maximum edge weight on the path between any two specials. That is equivalent to: Among all edges in the MST, which one is the minimum weight that separates the set S into two non-empty groups? Actually, the maximum bottleneck between two specials is the maximum over paths of the max edge; i.e., it's the weight of the heaviest edge on the path connecting two specials. The maximum over all pairs will be the weight of the edge in the MST that is the largest such that there exist specials on both sides of that edge. In other words, if we consider the process of Kruskal (adding edges in increasing order), when we first connect all special vertices into a single component (i.e., become connected among themselves via the MST edges), the weight of the last added edge that causes the specials to become connected is the answer. Because as we add edges from smallest to largest, initially each special is isolated, then as we add edges, they become connected. The moment all specials belong to the same component (i.e., they are all connected via edges added so far), the maximum edge weight used on the paths among them is at most the maximum edge weight added so far. And the smallest possible maximum edge weight needed to connect all specials (i.e., the minimax connection) is the weight of the edge that completes the connectivity among specials in the MST. This is similar to building a minimum spanning tree on the specials only? But we have the whole graph.
Actually, we can compute the answer directly by processing edges sorted by weight and performing union-find (like Kruskal) but stop when the number of components containing specials reduces to 1, i.e., all specials are in the same component. The weight of the edge that caused that is the answer. But careful: The distance between two specials is the minimum possible maximum edge weight, which is exactly the weight of the heaviest edge on the path in the MST. For the farthest pair, we need the maximum over all pairs of that distance. That maximum is the maximum edge weight on the tree that lies on some path between two specials. This is essentially the maximum edge weight among edges that lie on the minimal subtree spanning all specials (the Steiner tree connecting the specials). Because any two specials will have a path within that subtree; the maximum edge weight on that subtree is the diameter? Not exactly: Consider a tree where specials are leaves, and there is a high weight edge in the middle. The maximum distance between any two specials will be that high weight if both sides have at least one special. So the answer is the maximum edge weight on the minimal subtree that connects all specials (i.e., the union of paths between all specials). Indeed, that's the weight of the heaviest edge in that Steiner tree. Because for any two specials, the path is contained in that Steiner tree, and the maximum edge weight on that path is at most the maximum edge weight in the whole Steiner tree. And there exists a pair of specials whose path includes that maximum edge (e.g., pick two specials on opposite sides of that edge). So answer = maximum edge weight in the Steiner tree connecting specials (on the MST). This can be computed by building the MST and then doing a DFS or something to compute the max edge along the unique paths between specials.
Alternatively, as we argued using union-find: Process edges in increasing order, union components. For each component, we can keep count of special vertices in that component. Initially each vertex has count 1 if special else 0. As we union, we combine counts. The moment we have a component whose special count equals k (i.e., all specials are in the same component), the current edge weight is the answer. Because when all specials become connected, the maximum edge weight needed to connect any two specials via the edges added so far is at most that weight, and it's minimal? Wait, we want the maximum over all pairs of the minimax distance. That equals the minimal weight such that the specials are all connected (i.e., the threshold where the subgraph with edges of weight ≤ W makes all specials connected). Because for any two specials, the minimax distance is the minimum W such that they are connected using edges of weight ≤ W. So the distance d(u,v) = the smallest W such that u and v are in the same component of the graph formed by edges of weight ≤ W. Then the maximum over pairs is the smallest W such that for every pair of specials they are connected? Actually, the maximum over pairs of d(u,v) is the smallest W such that the graph with edges ≤ W has all specials in one component (i.e., they are pairwise connected). Because if all pairs are connected with edges ≤ W, then max d(u,v) ≤ W. And if some pair requires > W, then they are not in same component. So the max distance among specials is exactly the threshold weight where the specials become all connected when considering edges up to that weight. This is exactly the definition of the "bottleneck Steiner tree" or the "minimum spanning tree on the set of specials" but using the original graph distances? Actually, it's the value of the maximum edge weight in the minimum spanning tree of the specials if we consider the complete graph with distances = minimax distances. But we can compute it by union-find on sorted edges.
Thus, we can compute answer by:
- Read edges.
- Sort edges by weight ascending.
- Initialize DSU with n nodes.
- For each vertex, maintain count of specials in its component.
- Iterate over edges in increasing weight, union their components (skip if already same).
- After each union, if the combined component's special count becomes k, then answer = current edge weight, and break.
- Then output answer repeated k times.
Check: In example 2: edges sorted: (4-2 w=1), (2-3 w=2), (1-3 w=3), (1-4 w=4), (1-2 w=5). Process: start each node special? nodes 1,2,3 are special, 4 is not. special counts: comp(1)=1, comp(2)=1, comp(3)=1, comp(4)=0.
Edge 1: 4-2 weight=1: union comps (2) and (4). New component special count = 1 (from node2) +0 =1. Not all.
Edge 2: 2-3 weight=2: now 2 is in comp with 4 (special count=1), 3 is special count=1. Union: total special count =2, not all.
Edge 3: 1-3 weight=3: component of 1 (special count=1) and component of 3 (which now includes 2,4, special count=2) union => total special count =3 = k. So answer=3. So output 3 3 3. Matches.
Example 1: n=2, specials: 1,2. edges: (1,2,3),(1,2,2),(2,2,1) but note self-loop (2,2,1) does not connect different vertices, so union doesn't change? But we can ignore self-loops and multiple edges, they are fine. Sorted: (2,2,1) self-loop skip? Actually union find would treat u==v, but no need to union same node. So next edge (1,2,2): union comp1 and comp2, special count becomes 2 => answer=2. Output 2 2. Works.
Thus the problem reduces to computing the weight at which all specials become connected in the threshold graph. This is independent of per-special answer, all get same.
But careful: Is it always true that the farthest distance for a special vertex is exactly this global diameter? We argued using ultrametric property derived from MST. But what if the graph is not a tree? However, as argued, the distance metric (minimax) is the same as in any MST. And the MST's distances are ultrametric. So indeed, for any set S, for any x in S, max_{y in S} d(x,y) = max_{u,v in S} d(u,v). Let's double-check with a non-tree graph where MST might have same distances but maybe the ultrametric property fails? Actually the distance metric is defined on the graph and is equal to the MST distances, so it inherits the ultrametric property from the tree representation. So it's correct.
Thus, the answer for each special is the same. So we can output the same value k times.
But wait: The problem statement says: "For each special vertex, find another special vertex which is farthest from it and output the distance between them." It doesn't explicitly say that the farthest distance is same for all; but as per reasoning, it is. So we just compute that maximum distance.
Edge Cases: There may be multiple edges and self-loops. Self-loops don't affect connectivity, so we can ignore them in union-find (or just skip when u==v). Also multiple edges: just treat as separate edges; when sorting, we may have many, but it's fine.
Complexities: n,m up to 1e5, sorting m edges O(m log m) fine.
But need to be careful: The DSU union should be done efficiently. Also initial special count: boolean array special.
Implementation steps:
- Read n, m, k.
- Read list of k special vertices (distinct). Possibly store a boolean array is_special[1..n] or a set.
- Initialize DSU with parent and size maybe, plus special_count array.
- For each vertex i from 1 to n: parent[i]=i, special_count[i] = 1 if i is special else 0.
- Read all edges (u, v, w). If u != v, store edges in list (u, v, w). If u == v, skip because it doesn't connect different components. (Actually self-loop can be ignored for connectivity.)
- Sort edges by w ascending.
- Iterate through edges:
- Find root of u, root of v.
- If root_u == root_v, continue.
- Merge: typically attach smaller size to larger.
- Update special_count of new root = special_count[root_u] + special_count[root_v].
- If special_count[new_root] == k, then answer = w, break.
- After loop, output answer repeated k times separated by spaces. (Edge case: if after processing all edges we still haven't got all specials connected? But graph is connected, so after processing all edges, all vertices are in one component, and that component will have special_count = k, so we will definitely break at some point. So safe.)
But note: There might be edges with equal weight. The moment we union and get all specials, we output that weight. However, there could be multiple edges with same weight; the answer is that weight. It's fine.
Thus, this solves the problem with O(m log m) time, O(n) memory.
But wait: Could there be a scenario where the farthest distance from a special vertex is not the global diameter? Let's test with a more complex set that does not satisfy ultrametric? The metric is ultrametric, so it should hold. However, consider a set of four specials: distances might be: some pairs have smaller distances but the maximum might be D. For any point x, there exists at least one point y such that d(x,y)=D, as argued using the pair achieving D. So yes, max distance from any x is D.
But check: The ultrametric property we used: For any triple, the two largest distances are equal. This is known to hold for bottleneck distances on trees. But is it always? Let's try to find a counterexample. Consider a tree where the specials are not all leaves; maybe three specials: a,b,c with distances: a-b=5, a-c=5, b-c=3 (as before). So D=5. For b, max is 5. For all, max=5. So OK.
Consider four specials: a,b,c,d with tree shaped like: edges: a-x(2), x-y(5), y-b(1), y-c(3), and also d attached to y with weight 4. So specials a,b,c,d. Compute distances: a-b: max(2,5,1)=5; a-c: max(2,5,3)=5; a-d: max(2,5,4)=5; b-c: max(1,3)=3; b-d: max(1,4)=4; c-d: max(3,4)=4. So D=5. For a, farthest=5. For b, farthest = max(5,3,4)=5; for c, farthest = max(5,3,4)=5; for d, farthest = max(5,4,4)=5. So all have 5.
What about if the specials are all on one side of the heaviest edge? Then the heaviest edge might not be on any path between specials; D would be less. But then no special is on the other side, so that heavy edge is not included in the Steiner tree. So global D is determined by the heaviest edge that separates specials into two non-empty groups. That edge will be in the Steiner tree. For any special on one side, there is at least one special on the other side, giving distance at least that weight. So again each special sees that weight from some other special.
Thus consistent.
Hence the answer is same for all.
But before finalizing, we must verify that the distance defined is indeed the minimax path cost. Yes. And the MST property holds: The minimum bottleneck path between two vertices is the maximum edge weight on the path in any MST. This is a known fact. Proof: In any graph, the minimum possible maximum edge weight over all paths between two vertices equals the minimum W such that they are connected using edges of weight ≤ W. Consider Kruskal's algorithm: The MST includes edges in order of increasing weight; the moment two vertices become connected in the MST construction (i.e., when they first belong to same component), that edge weight is the threshold W for them to be connected using edges ≤ W. Actually the threshold is the maximum weight edge on the path in the MST. So it's correct.
Thus algorithm is correct.
But we must be careful: The graph may have up to 1e5 edges, but n up to 1e5. Sorting is fine. DSU with path compression and union by size is fine.
Potential pitfalls: The answer could be large, up to 1e9, so store in int64? But output as integer.
Edge Cases: k could be n (all vertices special). Then answer is the weight of the last edge added before the whole graph becomes one component? Actually if all vertices are special, then we need the maximum bottleneck distance among all vertices. That would be the weight of the heaviest edge in the MST? Wait, if all vertices are special, then the farthest distance for any vertex is the diameter of the whole tree under bottleneck. In an ultrametric, the maximum distance between any two vertices is the weight of the heaviest edge in the MST? Actually in a tree, the maximum bottleneck distance between any two vertices is the maximum edge weight in the tree, because there will be a pair of vertices on opposite sides of that heaviest edge. So answer is the maximum edge weight in the MST. But using our union-find method: we stop when special_count == n, i.e., when all vertices are in one component. That would happen at the last union that connects the final two components. The weight of that edge is the maximum edge weight in the MST (since edges are added in increasing order, the last edge added is the heaviest edge in the MST). So answer = weight of last edge added (if we break at that moment). However, is that the maximum bottleneck distance among all vertices? Consider if the MST has multiple heavy edges; the maximum bottleneck distance might be determined by the heaviest edge. So indeed answer is that weight. So it matches.
But note: When all vertices are special, our union-find break condition will trigger at the edge that makes the component contain all n vertices. That is correct.
Now about self-loops and multiple edges: we can skip self-loops entirely because they never connect different components. Multiple edges: we treat them as separate edges; when sorted, the smaller weight will be considered first; that's fine.
Therefore, we have an extremely simple solution.
But is there any subtlety? The problem statement: "It is guaranteed that the graph is connected." So MST exists and we'll eventually connect all.
Thus we can implement.
But wait, we should confirm that the farthest special vertex is defined as "another special vertex", i.e., the farthest must be a different special. In the case of k=2, obviously both have each other as farthest, and distance is the distance between them. In case of more than 2, and if for some special, the farthest distance could be to itself? Not allowed because another. But as argued, there exists another special at distance D. So it's fine.
Now, I recall that there is known Codeforces problem "Chloe and pleasant prizes" or something? Actually this problem is from Codeforces: "Chouti and his homework" maybe? The problem ID: 1196F? Not sure. But I've seen a problem "Bottleneck" maybe. Anyway, the solution is as described.
But wait, we must be absolutely certain about the ultrametric property for any graph? Let's prove carefully:
Given an undirected graph with edge weights, define d(u,v) = min_{paths P from u to v} max_{e in P} w(e). This is known as the minimax distance. It satisfies the triangle inequality: d(u,w) ≤ max(d(u,v), d(v,w))? Actually, we need to prove d(u,w) ≤ max(d(u,v), d(v,w)). Let d1 = d(u,v), d2 = d(v,w). For any ε>0, there exists a path from u to v with max weight ≤ d1+ε, and similarly from v to w with max ≤ d2+ε. Concatenating gives a path from u to w with max weight ≤ max(d1+ε, d2+ε) = max(d1,d2)+ε. So d(u,w) ≤ max(d1,d2)+ε for any ε>0, thus d(u,w) ≤ max(d1,d2). So indeed the strong triangle inequality holds. So d is an ultrametric (since also d(u,v)=d(v,u), d(u,u)=0, and if graph is connected all distances finite). So we have an ultrametric without needing MST! Good. So we can directly use the property: For any three points u,v,w, d(u,w) ≤ max(d(u,v), d(v,w)). This is all we need for the earlier argument: Suppose a,b are such that d(a,b) = D (maximum). For any x, by the inequality: D = d(a,b) ≤ max(d(a,x), d(x,b)). Since D is the maximum possible, we have max(d(a,x), d(x,b)) ≥ D, but also ≤ D? Actually, d(a,x) ≤ D and d(x,b) ≤ D because D is maximum. So max(d(a,x), d(x,b)) ≤ D. So from D ≤ max(d(a,x), d(x,b)) ≤ D, we get max(d(a,x), d(x,b)) = D. Therefore at least one of d(a,x) or d(x,b) equals D. So indeed, for any x, there exists either a or b with distance D. So the maximum distance from x to any other point is at least D, and at most D, so exactly D. So we have proven that without referencing MST. Great! So the answer for all special vertices is the same: the diameter D = max_{i,j} d(x_i, x_j). So we just need to compute D.
Thus our union-find threshold method is valid: D = min W such that all specials are in the same component of the graph using edges with weight ≤ W. Because d(x_i, x_j) ≤ W iff they are connected by edges ≤ W. So the maximum d is the minimal W that makes the specials all pairwise connected. That's exactly the threshold where the specials become all in one component.
Therefore, we can solve without even building MST: just sort edges by weight and union until specials merged.
This is even simpler.
Time complexity: O(m log m + m α(n)). Acceptable.
Now we should think about potential issues: The graph may have multiple edges connecting same vertices, some with lower weight; that's fine.
Edge Cases: If there is an edge with weight 0? Constraint says w ≥ 1, so all positive.
Check: The answer might be output as 64-bit? w up to 1e9, so int fits in 32-bit signed? 1e9 < 2^31, so 32-bit signed int works. But may sum something? Not needed. So int fine.
Implementation details:
We'll read input using fast I/O (sys.stdin.buffer). In Python, we can implement DSU.
Steps in code:
def solve():
import sys
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
k = int(next(it))
specials = [int(next(it)) for _ in range(k)]
is_special = [0]*(n+1)
for v in specials:
is_special[v] = 1
edges = []
for _ in range(m):
u = int(next(it)); v = int(next(it)); w = int(next(it))
if u != v:
edges.append((w, u, v))
edges.sort() # sort by w
parent = list(range(n+1))
size = [1]*(n+1)
special_cnt = is_special[:] # copy list
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b, w):
ra = find(a); rb = find(b)
if ra == rb:
return False
# union by size
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
special_cnt[ra] += special_cnt[rb]
# optional: we don't need to update special_cnt[rb] because it's not root
return special_cnt[ra] == k
ans = 0
for w, u, v in edges:
if union(u, v, w):
ans = w
break
# output ans repeated k times
out = ' '.join([str(ans)] * k)
sys.stdout.write(out)
But careful: In union, we used w parameter not needed; we just need to check condition after union. However, we should break after we set ans = w, but we also need to be careful that if the condition becomes true after union, that's the answer. However, we must also consider that there might be edges with same weight; if we break at the first time we achieve k specials, that's correct because the weight is the current edge weight which is the threshold. But what if we achieve k specials after merging two components that both had specials, and the total special count becomes k, but there may be multiple edges of same weight and the condition could be satisfied earlier? Actually, sorting ascending, we process edges from smallest to largest weight. The first time we achieve all specials in one component, the weight of the edge that caused it is the minimal W such that the specials are all connected. So that's the answer. If there are multiple edges with same weight, and after processing some edges of weight w, we might have all specials connected, but perhaps the first edge of that weight might have triggered it. Then answer = w. That is correct.
But we must ensure that if the specials are already all in same component initially? Not possible because initially each node is separate, and there are at least 2 specials, so they are not all in one component. So we will always have to union at least once.
One more nuance: If there are multiple edges with same weight, and after processing an edge of weight w we achieve connectivity, answer is w. But suppose the connectivity is achieved not because of the edge we just added but because of previous edges? Actually, connectivity increases monotonically. The moment we achieve all specials in one component, it happens exactly when we union two components that together contain all specials. So it's due to that union. So answer is weight of that union.
Thus algorithm correct.
But what about self-loop edges? We skip them. Could they matter? No, they don't connect distinct vertices, so they never increase connectivity.
Now, let's test on a custom case: n=3, m=3, k=2, specials: 1,3. edges: (1,2,10), (2,3,5), (1,3,20). Sorted: (2,3,5), (1,2,10), (1,3,20). Process: first edge (2,3,5): union 2 and 3, component special count: 2 has 0? Actually 2 not special, 3 special => component of 3 gets count=1. Component 2? Initially special counts: 1 has 1, 2 has 0, 3 has 1. After union(2,3): root of 2 and 3 combine; whichever root, count becomes 1 (since 3's special). Not all. Next edge (1,2,10): find(1) (count 1) and find(2) which is in component with 3 (count 1) => total special count =2 => answer=10. However, the actual distance between 1 and 3: minimax path could be via edge (1,3) weight 20 (max=20) or via 1-2-3 with max = max(10,5)=10. So min max is 10. So max distance among specials (only pair) is 10. So answer 10 correct. Good.
Now, another test: n=4, edges: 1-2(1), 2-3(2), 3-4(3). k=4 all specials. Sorted edges: (1,2,1) -> special counts? after union: comp with {1,2} special count=2 (since both special). Not all. Next (2,3,2): union comp containing 1,2 (count2) and node3 (special count1) => total specials=3. Not all. Next (3,4,3): union comp with {1,2,3} (count3) and node4 (count1) => total=4 => ans=3. Indeed the maximum bottleneck distance between any two nodes is 3 (e.g., 1-4 path max=3). So answer=3.
Now, if k=3 specials: 1,2,4. Using same graph: distances: 1-2:1, 1-4: max(1,2,3)=3, 2-4: max(2,3)=3. Diameter=3. Process edges: After (1,2,1): comp(1,2) special count=2. After (2,3,2): union comp(1,2) with 3 (non-special) => special count still 2. After (3,4,3): now comp(1,2,3) (count2) union with 4 (special count1) => total specials=3 => ans=3. Works.
Thus solution seems straightforward.
But wait: The problem statement might be from Codeforces Round #541 (Div. 2) maybe? Actually I recall a problem "Chloe and the sequence"? No. There is a problem "1195C" not sure. But the described problem appears in Codeforces as "1192B? Actually I think it's from Codeforces Round #549 (Div. 1) problem A? No.
Let's search memory: There's a problem "1196F" is "K-th Path". Not this. There's "1192C" maybe not. Anyway.
But I recall a known trick: In a graph, the minimax distance (also called the minmax path) can be computed via MST. And the property that all farthest distances equal the diameter in ultrametric is known.
Given that constraints are up to 1e5, the solution is O(m log m) which is fine.
Now, we need to output k integers: for each special vertex, the farthest distance. As we argued, it's same for all, so we output the computed answer k times.
We must be careful: The order of output should correspond to the order of specials as given in input. So we output the same number for each.
Now, let's verify with example 2: specials order: 1 2 3. Output "3 3 3". Yes.
Now, check if any tricky case: The graph may have parallel edges with same weight, but we skip self-loops only; parallel edges are fine. The DSU union may be invoked on edge connecting vertices already in same component due to previous edges. In that case we skip. Good.
Potential issue: If k=0? Not allowed, k≥2.
Edge Cases: If m = n-1 (tree) then MST is the tree itself. But still our union-find method yields answer as weight of edge that connects last two special components. Works.
Now, confirm that the answer is indeed the minimal W such that specials are all connected using edges ≤ W. This is equivalent to the maximum minimax distance among specials. Since for any pair, d(u,v) = min W_{uv} such that they are connected by edges ≤ W_{uv}. Then the maximum over pairs of d(u,v) is the minimal W such that for all pairs, they are connected, i.e., all specials are in one component. So yes.
Thus implementation is correct.
Now, we can also consider alternative approach: build MST and then find the maximum edge on the Steiner tree via BFS/DFS from any special and then find farthest special? But our method is simpler.
Thus final solution: sort edges, union-find, break when all specials in one component, output weight.
But wait: Is there any scenario where the threshold W that connects all specials is not equal to the maximum d(u,v)? Because to have all pairs connected, we need the graph on edges ≤ W to have the specials in one component. That is equivalent to saying the maximum d(u,v) is ≤ W, and the minimum W for which this holds is exactly the maximum d(u,v). So yes.
Now, confirm that the union-find approach indeed finds the minimal W because we add edges in increasing order; the first time the specials become all connected, the current weight is the minimal W.
Hence solved.
Now let's consider possible pitfalls with DSU: The special_cnt should be maintained per root. When we union, we need to add counts. Implementation as above is fine.
Now, think about large input: m up to 1e5, reading with sys.stdin.buffer is okay. Sorting m edges O(m log m) fine.
Now, one more nuance: The problem may have multiple test cases? The input description does not indicate multiple test cases, so single case.
Now, let's test with random small graphs to ensure correctness. But I'm confident.
Before finalizing, I want to think if there is any subtle condition that could break the ultrametric argument. The inequality d(u,w) ≤ max(d(u,v), d(v,w)) is proven. But does it guarantee that the two largest among three distances are equal? Let's derive: Consider three points a,b,c. Let d_ab, d_bc, d_ac. Without loss, suppose d_ab is the largest. Then by inequality, d_ac ≤ max(d_ab, d_bc) = d_ab (since d_ab is largest). Similarly, d_bc ≤ max(d_ab, d_ac) = d_ab. So the largest is d_ab. But could d_ac be less than d_ab, and d_bc also less than d_ab, and d_ab > both? That is possible. For ultrametric, we require that the two largest are equal. So we need to prove that at least one of the other distances equals d_ab. Using the inequality d_ab ≤ max(d_ac, d_bc). Since d_ab is the largest, we have d_ab ≤ max(d_ac, d_bc). But max(d_ac, d_bc) ≤ d_ab, so we get d_ab = max(d_ac, d_bc). Therefore, at least one of d_ac or d_bc equals d_ab. So indeed the two largest are equal (if d_ab is the maximum, then max(d_ac, d_bc) = d_ab, meaning either d_ac = d_ab or d_bc = d_ab). So property holds. So it's ultrametric.
Thus proof is solid.
Hence final answer.
Now, in the output, we need k integers separated by spaces. For each special, answer is same.
Potential nuance: The problem may require that we output for each special vertex the distance to the farthest special vertex, not including itself. As argued, for each special, the farthest distance is the diameter, which is achieved with some other special. So fine.
Now, I'm ready to write final solution.
But let's check the first example again: Input:
2 3 2
2 1
1 2 3
1 2 2
2 2 1
Our method: edges: (1,2,3), (1,2,2), (2,2,1). We skip self-loop (2,2). So we add (1,2,2) and (1,2,3). Sorted: (1,2,2), (1,2,3). Process first edge (1,2,2): union components: special counts: node1 special? Actually specials: 2,1, both specials. So after union, component special count=2, ans=2. So output 2 2. Works.
Now, if there were only two specials and a self-loop edge with weight 1, the answer still would be the minimum edge weight connecting them, not the self-loop. So correct.
Now, we should handle the case where the graph has a direct edge between two specials with weight 5, but also a longer path with lower bottleneck? Actually bottleneck distance is the minimum max edge weight, so we would choose the better path. So threshold method accounts for that because it adds edges in increasing order; if there is a path using lower weight edges that connects the specials, they will become connected earlier (at lower weight) than the direct heavy edge. So the answer will be the minimal weight threshold, i.e., the bottleneck of the best path. Good.
Thus all good.
Now, could there be a scenario where after adding edges, the specials become all connected but the current edge weight is not the answer? Because the threshold is the maximum edge on the path that connects them; but if the specials become all connected at weight w, that means there exists a path between any two specials using only edges ≤ w. Therefore, for each pair, d(u,v) ≤ w. Moreover, before adding this edge, they were not all connected, meaning there existed at least one pair of specials not yet connected via edges ≤ w- (or previous weight). But note that weights are integers, but could be any numbers; but since we add in ascending order, the moment we add edge of weight w, we achieve connectivity. That implies that for some pair, any path connecting them must have a maximum edge weight at least w; otherwise they would have been already connected via edges ≤ w-? However, there could be edges with weight exactly w that were added earlier? Actually we process all edges ≤ w before adding this edge? Wait, we sort edges, and we are iterating through them. When we process edge with weight w, we have already processed all edges with weight < w (if any). So before processing this edge, the graph using edges with weight < w is already present. If after processing all those edges, the specials are not all connected, then there exists at least one pair of specials that are not connected using edges < w. That means for that pair, the minimal possible max edge weight is at least w (since any connecting path must include at least one edge of weight ≥ w). But could it be exactly w? Yes, because we are about to add an edge of weight w that will connect them (maybe via that edge or some combination). So the distance for that pair is exactly w. Therefore, the maximum distance among specials is w. So answer = w. So it's correct.
Thus algorithm stands.
Now, time to write final answer.
We need to be careful about Python recursion depth? Not needed, DSU uses loops.
Potential pitfalls: We may store edges as tuple (w, u, v) and sort. For large m, fine.
Now, handle the case where there is an edge with u==v (self-loop) we skip it because it never connects distinct components. However, what if the only way to connect two components is via a self-loop? That doesn't make sense, self-loop stays within same vertex. So skipping is fine.
One more nuance: If k=0? Not possible.
Edge Cases: k could be 1? But constraints say k≥2. So ignore.
Now, implement.
Let's write code:
def solve():
import sys
data = sys.stdin.buffer.read().split()
if not data: return
it = iter(data)
n = int(next(it))
m = int(next(it))
k = int(next(it))
specials_input = [int(next(it)) for _ in range(k)]
is_special = [0]*(n+1)
for v in specials_input:
is_special[v] = 1
edges = []
for _ in range(m):
u = int(next(it))
v = int(next(it))
w = int(next(it))
if u != v:
edges.append((w, u, v))
edges.sort(key=lambda x: x[0]) # sort by weight
parent = list(range(n+1))
size = [1]*(n+1)
cnt_special = is_special[:] # copy counts
def find(x):
# iterative path compression
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(u, v):
ru = find(u)
rv = find(v)
if ru == rv:
return False
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru
size[ru] += size[rv]
cnt_special[ru] += cnt_special[rv]
return cnt_special[ru] == k
ans = 0
for w, u, v in edges:
if union(u, v):
ans = w
break
# Output
out = ' '.join([str(ans)] * k)
sys.stdout.write(out)
if name == "main":
solve()
We need to ensure that we break after setting ans, but there might be case where after union we haven't reached k but later edges also have same weight w; we break only when condition true. That's fine.
Now, consider scenario where edges list is empty? Not possible because graph connected and m >= n-1 >=1.
Now, check time: Sorting edges up to 1e5, union-find operations O(m α(n)). Acceptable.
Now, test with given examples.
Example 1:
Input:
2 3 2
2 1
1 2 3
1 2 2
2 2 1
Our code reads: n=2,m=3,k=2, specials [2,1]. is_special[1]=1, is_special[2]=1.
Edges: (1,2,3) => u!=v, add (3,1,2); (1,2,2) add (2,1,2); (2,2,1) skip. sort => (2,1,2), (3,1,2).
Process (2,1,2): union(1,2). ru=1, rv=2, merge. cnt_special[1] initially 1, cnt_special[2]=1, after merging ru=1 (size bigger) gets count 2 -> equals k -> ans=2, break. Output "2 2". Good.
Example 2:
Input:
4 5 3
1 2 3
1 2 5
4 2 1
2 3 2
1 4 4
1 3 3
Our parsing: Actually the second line is specials: "1 2 3". Then edges: next lines:
1 2 5? Wait, need to double-check input from problem statement:
Second example Input:
4 5 3
1 2 3
1 2 5
4 2 1
2 3 2
1 4 4
1 3 3
Let's parse: first line: 4 5 3
second line: 1 2 3 (specials)
Then 5 lines of edges:
1 2 5
4 2 1
2 3 2
1 4 4
1 3 3
Yes.
So specials: 1,2,3.
Edges list: (5,1,2), (1,4,2)?? Actually 4 2 1 => (1,4,2) weight=1, u=4, v=2. (2,3,2) => (2,2,3)? Actually it's "2 3 2" => (2,2,3) weight=2, u=2, v=3. (1,4,4) => (4,1,4) weight=4, u=1, v=4. (1,3,3) => (3,1,3) weight=3, u=1, v=3.
Also (1,2,5) => (5,1,2).
Now sorted by weight: (1,4,2), (2,2,3), (3,1,3), (4,1,4), (5,1,2). Process:
-
(1,4,2): union(4,2). components: 4 (non-special) and 2 (special). After union, root say 2, cnt_special=1? Actually 2 is special so count=1, 4 not => total=1? Wait initial counts: 1:1,2:1,3:1,4:0. After union(4,2): root of 2 maybe 2, root of 4=4, merge. New root (2) count = 1+0=1. Not k.
-
(2,2,3): union(2,3). Find(2) root maybe 2 (since 2 is in component with 4, but root could be 2 if we attached 4 to 2). Find(3) root 3. Both special: cnt_special[2]=1, cnt_special[3]=1. Merge, root say 2 (if size bigger), count becomes 2. Not k.
-
(3,1,3): union(1,3). Find(1) root 1 (count=1). Find(3) root now is 2? Because 3 merged with 2, so root 2, count=2. Merge 1 and 2: after union, root say maybe 2 (size larger) count becomes 1+2=3 = k. So ans=3. Output "3 3 3". Good.
Thus solution works.
Now, think about potential memory: edges list length up to m (1e5) and storing as tuples of three ints is fine.
Now, note that we used cnt_special as list of length n+1. In union, we add counts from child to root. The child's count is not updated but that's fine as it's no longer root.
Now, ensure that we don't have any off-by-one: indices from 1 to n.
Now, final answer.
We can also avoid sorting by using bucket sort but not needed.
Now, let's consider if the answer can be 0? Edge weights at least 1, so answer >=1. So fine.
Now, we can finalize.
But wait: The problem statement says "The graph may have multiple edges and self-loops." Our code skips self-loops, which is fine. But what about multiple edges? That's fine, we treat them as separate. However, one subtlety: If there is an edge with weight less than the threshold but connecting vertices already connected, it doesn't matter. So it's fine.
Now, test with random small graphs to double-check. Let's simulate a case: n=5, edges: (1-2,1), (2-3,2), (3-4,3), (4-5,4). Specials: {1,5}. The answer should be 4? Actually distance between 1 and 5: path max = max(1,2,3,4)=4. So diameter =4. Our method: sort edges: (1,2) w1, (2,3) w2, (3,4) w3, (4,5) w4. Process: after 1-2: component {1,2} special count=1 (only 1). after 2-3: union component {1,2} with {3} -> special count still 1. after 3-4: union with {4} -> special count still 1. after 4-5: union component containing {1,2,3,4} (special count 1) with {5} (special count 1) -> total 2 => ans=4. Good.
Now consider another graph where there is a cheaper path: 1-2 weight 5, 1-3 weight 1, 3-2 weight 1. Specials: {1,2}. The distance between 1 and 2: path 1-3-2 max=1, so answer=1. Our method: edges sorted: (1,1,3) weight1, (1,3,2) weight1, (5,1,2) weight5. Process first edge (1,1,3): union 1 and 3, special count: 1 is special, 3 not -> count=1. Second edge (1,3,2): union component (1,3) (count=1) with node2 (special) => total special count=2 => ans=1. Good.
Now, consider specials more than 2, but the threshold edge might connect two components each containing multiple specials. Works.
Now, check for integer overflow? Not an issue.
Now, final solution.
But wait: The problem originally might have had different interpretation? Let's read problem statement again: "Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them." That's exactly what we used. Then "For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them." So we compute farthest distance.
Thus our solution stands.
Now, one more nuance: Could there be a tie? Doesn't matter.
Now, check the note: In second example, distance between 2 and 3 is 2. For vertex 2, farthest is 3 (to 1) distance 3. So all specials output 3.
Thus final.
Now, there's a possibility that the graph is not a tree and there may be multiple MSTs, but the distance metric is unique regardless of MST. Our union-find threshold method does not even require building MST; it's directly computing the threshold.
Now, check constraints: n up to 1e5, m up to 1e5. Sorting edges O(m log m) ~ 1e5 * 17 ~ fine.
Now, I'd like to consider the possibility of needing to output the farthest distance for each special separately if they were not equal. But our proof says they are equal. So we are good.
But is there any hidden condition that might break the ultrametric property? Let's check the inequality d(u,w) ≤ max(d(u,v), d(v,w)). In proof, we considered any ε > 0, take a path P1 from u to v with max ≤ d(u,v)+ε, and P2 from v to w with max ≤ d(v,w)+ε. Then concatenation gives a path from u to w with max ≤ max(d(u,v), d(v,w)) + ε. So d(u,w) ≤ max(d(u,v), d(v,w)) + ε for any ε, hence d(u,w) ≤ max(d(u,v), d(v,w)). That's correct. However, note that the concatenated path might repeat vertices/edges, but that's fine; it's still a path (walks are allowed? Usually paths are simple? The definition of path in graph typically means a sequence of vertices where each consecutive pair is an edge; but can it repeat vertices? Typically "path" means simple path with no repeated vertices? In the definition of distance, they likely consider any walk? Usually, in graph theory, "path" is simple, but the definition of distance as minimum over all paths (simple) is fine. However, if we concatenate two simple paths, the result might not be simple (could have cycles). But we can always remove cycles without increasing the maximum edge weight (since removing edges cannot increase max). So there exists a simple path with max ≤ that of the walk. So we can still find a simple path with max ≤ max(d(u,v), d(v,w)) + ε. So inequality holds. So proof stands.
Thus ultrametric property holds for the set of all vertices under this distance.
Now, is the condition "find another special vertex" implying we cannot consider the same vertex? So we need distance to another. But as argued, the maximum distance for a vertex is achieved by some other vertex; in case of multiple vertices at same maximum distance, still another exists. So fine.
Now, could there be a case where a special vertex is isolated from others? Graph is connected, so no.
Thus final solution.
Now, we need to produce a clean explanation and code. The solution is basically: sort edges, use DSU, stop when all specials are in one component, output that weight for each special.
But wait: There is one subtle case: If there are multiple edges with same weight, we might achieve connectivity after processing one of them, but there might be an earlier edge of the same weight that didn't achieve connectivity but later edge of the same weight does. Since we break at the first edge that yields connectivity, we output that weight. All edges of that weight have the same weight, so answer is that weight. That's correct.
Now, check if there could be an edge of weight w that connects two components each with some specials, resulting in total specials count = k, but there might be a smaller weight that also connects all specials? That would contradict that we haven't yet connected them before; because if there exists a smaller weight edge that connects all specials, then after processing all edges with smaller weight, they would already be connected. Since we processed all smaller weights before, they are not all connected, so no such smaller weight exists. So answer is minimal.
Thus done.
Now, I'll produce final answer.
But just to be thorough, let's consider if there is any scenario where the specials become all connected not through a direct union of two components, but because of multiple unions within the same weight? For example, suppose we have weight w edges only, and after processing some of them, the specials become connected. The first edge that causes the special count to reach k is the one we break at. That edge's weight is w, which is the answer. If we break at that point, we output w. However, could it be that the actual maximum distance is less than w? Because maybe the specials were already connected through a path that uses only edges with weight less than w, but we haven't yet realized it because our DSU only merges when we process edges. But if such a path existed, then after processing all edges with weight less than w, the specials would have been already in the same component. Because DSU exactly captures connectivity via edges processed so far. So if after processing all edges with weight < w they are not all connected, then there is no path using only edges < w that connects all specials. Therefore, some pair requires an edge of weight at least w. And the edge we added at weight w provides a path with max weight w (since all edges on that path are of weight ≤ w because we haven't added heavier edges yet). Actually careful: When we add an edge of weight w, the new component's connectivity may involve edges of weight ≤ w, but we may not have added some edges of weight exactly w that are also needed? However, we are adding edges in increasing order; all edges with weight < w have already been added. So any path formed after adding this edge might use other edges of weight w that are not yet added? But we haven't added them yet; however, the connectivity after adding this single edge only uses that edge plus previously added edges (all < w). Could the connectivity to connect all specials require more than one edge of weight w? Suppose after adding some edge of weight w, we connect two large components, each of which had internal connections using edges < w. That creates a new path between any two specials that may go through the newly added edge. The max edge on that path is w (if the new edge is the only one of weight w). However, if there is a special pair that needed two edges of weight w to connect, they would not be connected until both are added. But if we haven't added both, then after adding only one, they might still be disconnected. So the moment they become all connected, it might be after adding the second edge of weight w. In that scenario, the minimal weight that makes all specials connected is w, because it's possible that with some but not all w-edges, they are still not connected, but after enough w-edges they become connected. However, the answer remains w, as the threshold is w. The first time we achieve connectivity, we output w. That is correct. So breaking at the first union that yields count = k is okay.
But there is a nuance: Could the first union that yields count = k happen with an edge of weight w, but the actual maximum distance among specials is > w? That would imply that there is a pair of specials whose minimax distance is > w. If such a pair exists, then they are not connected using edges ≤ w. But after our union, we have connected all specials into one component using edges ≤ w (since all edges used so far have weight ≤ w). Therefore, any two specials are connected via a path consisting only of edges with weight ≤ w (the edges added so far). Hence their minimax distance ≤ w. Contradiction. So answer cannot be > w. And it is at least w because before that they were not all connected, so some pair required at least w. So answer = w.
Thus fine.
Now, final code.
Potential improvements: Use sys.setrecursionlimit but not needed.
Now, final answer: Provide explanation and code.
I'll prepare a final solution.
But wait, the problem originally may have had output not just the distance but also which vertex? No, just distance.
Thus solution is ready.
Now, I'll produce final answer: code in Python 3.
But ensure to handle reading fast.
Potential bug: When copying cnt_special as is_special[:], we must ensure it's a new list. is_special is list length n+1. That's fine.
Now, test with provided examples:
Example 1:
input_data = """2 3 2
2 1
1 2 3
1 2 2
2 2 1
"""
Our code returns "2 2". Good.
Example 2:
input_data = """4 5 3
1 2 3
1 2 5
4 2 1
2 3 2
1 4 4
1 3 3
"""
Our code returns "3 3 3". Good.
Now, test with random case where k=n=1e5? Not needed.
Now, final answer.
But there's an alternative: Using DSU with counting of specials.
Thus final solution.
Now, I'll produce the final response. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
k = int(next(it))
specials = [int(next(it)) for _ in range(k)]
is_special = [0] * (n + 1)
for v in specials:
is_special[v] = 1
edges = []
for _ in range(m):
u = int(next(it))
v = int(next(it))
w = int(next(it))
if u != v: # self-loops never help connectivity
edges.append((w, u, v))
edges.sort(key=lambda x: x[0]) # sort by weight ascending
parent = list(range(n + 1))
size = [1] * (n + 1)
cnt_special = is_special[:] # number of specials in each component (only valid for roots)
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(u: int, v: int) -> bool:
ru = find(u)
rv = find(v)
if ru == rv:
return False
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru
size[ru] += size[rv]
cnt_special[ru] += cnt_special[rv]
return cnt_special[ru] == k
ans = 0
for w, u, v in edges:
if union(u, v):
ans = w
break
# all specials receive the same answer
sys.stdout.write(' '.join([str(ans)] * k))
if name == "main":
solve()