1 #include <iostream>
2 #include <vector>
3 #include <cstdio>
4 #include <cstring>
5 #include <algorithm>
6 #include <cmath>
7 #include <map>
8 #include <set>
9 #include <string>
10 #include <queue>
11 #include <stack>
12 #include <bitset>
13 using namespace std;
14 #define pb(x) push_back(x)
15 #define ll long long
16 #define mk(x, y) make_pair(x, y)
17 #define lson l, m, rt<<1
18 #define mem(a) memset(a, 0, sizeof(a))
19 #define rson m+1, r, rt<<1|1
20 #define mem1(a) memset(a, -1, sizeof(a))
21 #define mem2(a) memset(a, 0x3f, sizeof(a))
22 #define rep(i, n, a) for(int i = a; i<n; i++)
23 #define fi first
24 #define se second
25 typedef pair<int, int> pll;
26 const double PI = acos(-1.0);
27 const double eps = 1e-8;
28 const int mod = 1e9+7;
29 const int inf = 1061109567;
30 const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
31 int n, k, m, f[10005];
32 int findd(int u) {
33 return f[u] == u?u:f[u] = findd(f[u]);
34 }
35 struct node
36 {
37 int u, v, c1, c2;
38 }a[20005], b[20005];
39 int check(int x) {
40 for(int i = 1; i<=n; i++)
41 f[i] = i;
42 int sum = 0, num = 0, cnt = 0;
43 for(int i = 0; i<m-1; i++) {
44 int u = findd(a[i].u);
45 int v = findd(a[i].v);
46 if(u == v)
47 continue;
48 if(a[i].c1<=x) {
49 num++;
50 sum++;
51 f[u] = v;
52 } else if(a[i].c2<=x) {
53 b[cnt++] = a[i];
54 }
55 }
56 if(num<k)
57 return 0;
58 for(int i = 0; i<cnt; i++) {
59 int u = findd(b[i].u);
60 int v = findd(b[i].v);
61 if(u!=v) {
62 f[u] = v;
63 sum++;
64 }
65 }
66 return (sum==n-1);
67 }
68 int main()
69 {
70 cin>>n>>k>>m;
71 for(int i = 0; i<m-1; i++) {
72 scanf("%d%d%d%d", &a[i].u, &a[i].v, &a[i].c1, &a[i].c2);
73 }
74 int l = 1, r = inf, ans;
75 while(l <= r) {
76 int mid = l+r>>1;
77 if(check(mid)) {
78 r = mid-1;
79 ans = mid;
80 } else {
81 l = mid+1;
82 }
83 }
84 cout<<ans<<endl;
85 return 0;
86 }