#include<bits/stdc++.h>
using namespace std;
inline int read(int &x)
{
static char c;
while (!isdigit(c = getchar())) ;
for (x = 0; isdigit(c); c = getchar()) x = x * 10 + c - 48;
return x;
}
const int MAXN = 1e5 + 5;
int N, K, M;
struct edge {
int u, v, w;
bool operator < (const edge &X) const {
return w < X.w;
}
} E1[MAXN], E2[MAXN];
int fa[MAXN];
int SZ[MAXN];
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
bool Check(int x)
{
for (int i = 1; i <= N; ++ i) {
fa[i] = i;
SZ[i] = 1;
}
int cnt = N;
for (int i = 1; i <= M; ++ i) {
if (E1[i].w > x) break;
int A = find(E1[i].u), B = find(E1[i].v);
if (A != B) {
if (SZ[A] < SZ[B])
fa[A] = B, SZ[B] += SZ[A];
else
fa[B] = A, SZ[A] += SZ[B];
cnt --;
}
}
if (N - cnt < K) return 0;
for (int i = 1; i <= M; ++ i) {
if (E2[i].w > x) break;
int A = find(E2[i].u), B = find(E2[i].v);
if (A != B) {
if (SZ[A] < SZ[B])
fa[A] = B, SZ[B] += SZ[A];
else
fa[B] = A, SZ[A] += SZ[B];
cnt --;
}
}
return cnt == 1;
}
int main()
{
read(N), read(K), read(M);
for (int i = 1, j; i < M; ++ i) {
E1[i].u = E2[i].u = read(j);
E1[i].v = E2[i].v = read(j);
E1[i].w = read(j);
E2[i].w = read(j);
}
sort(E1 + 1, E1 + M);
sort(E2 + 1, E2 + M);
int L = 1, R = 30000, ans = R;
while (L <= R) {
int mid = (L + R) >> 1;
if (Check(mid))
ans = mid, R = mid - 1;
else
L = mid + 1;
}
printf("%d", ans);
return 0;
}