Hint
Kruskal that stops earlier: add the edges by weight until the number of groups drops to k. The next edge that joins two different groups is the required distance – it is the shortest connection between the groups.
Solution (C++)
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <array>
using namespace std;
vector<int> parent;
int findSet(int v) { return parent[v] == v ? v : parent[v] = findSet(parent[v]); }
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<array<int, 3>> g(m); // {d, u, v}
for (auto &e : g) cin >> e[1] >> e[2] >> e[0];
sort(g.begin(), g.end());
parent.resize(n + 1);
iota(parent.begin(), parent.end(), 0);
int groups = n;
for (auto &e : g) {
int a = findSet(e[1]), b = findSet(e[2]);
if (a == b) continue; // already in the same group
if (groups == k) { // this edge joins two of the k groups
cout << e[0] << endl;
return 0;
}
parent[a] = b;
groups--;
}
return 0;
}