There are N bikers present in a city (shaped as a grid) having M bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only K bikers can be accommodated in the race. Jack is organizing the HackerRace and wants to start the race as soon as possible. He can instruct any biker to move towards any bike in the city. In order to minimize the time to start the race, Jack instructs the bikers in such a way that the first K bikes are acquired in the minimum time.
Every biker moves with a unit speed and one bike can be acquired by only one biker. A biker can proceed in any direction. Consider distance between bikes and bikers as Euclidean distance.
Jack would like to know the square of required time to start the race as soon as possible.
Input Format
The first line contains three integers, N, M, and K, separated by a single space.
The following N lines will contain N pairs of integers denoting the co-ordinates of N bikers. Each pair of integers is separated by a single space. The next M lines will similarly denote the co-ordinates of the M bikes.
Output Format
A single line containing the square of required time.
Constraints
1≤N≤250
1≤M≤250
1≤K≤min(N,M)
0≤xi, yi ≤107
SAMPLE INPUT
3 3 2
0 1
0 2
0 3
100 1
200 2
300 3
SAMPLE OUTPUT
40000
Explanation
There's need for two bikers for the race. The first biker (0,1) will be able to reach the first bike (100,1) in 100 time units. The second biker (0,2) will be able to reach the second bike (200,2) in 200 time units. This is the most optimal solution and will take 200 time units. So output will be 2002 = 40000.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve a problem: There are N bikers and M bikes on a grid. We need to assign K bikers to K distinct bikes such that the maximum time taken by any assigned biker to reach his assigned bike (under Euclidean distance, moving unit speed, so time = distance) is minimized. Actually the problem statement: "Jack can instruct any biker to move towards any bike... the first K bikes are acquired in the minimum time." This phrasing suggests we want to minimize the time until K biker-bike acquisitions have occurred, where bikers move simultaneously at unit speed. That is indeed the classic assignment problem: minimize the maximum distance among selected pairs (minimax). So we want the smallest T such that there exists a matching of size K where every matched pair distance ≤ T, and we want to output T^2 (since distances are Euclidean, but we can compute squared distances and compare to T^2). So we need to find the minimal possible maximum distance D for a matching of size K.
N and M ≤ 250, so we can compute all pairwise distances (squared) between bikers and bikes: N*M ≤ 62,500, which is fine.
We need to find minimal D^2 such that there exists a matching of size K in a bipartite graph where edges exist if squared distance ≤ D^2.
We can binary search over D^2 (since squared distances are integers if coordinates are integers? Euclidean squared distance = (x1-x2)^2 + (y1-y2)^2, which is integer. So we can binary search over the sorted list of all squared distances, or over range [0, maxDist^2]. Since coordinates up to 1e7, squared distances up to ~2*10^14, but that's within 64-bit.
We need to check for a given D^2, whether there is a matching of size K. That's bipartite matching (max flow). Since N,M ≤ 250, using Hopcroft–Karp O(E sqrt(V)) would be fine. For each check, we can build adjacency list of edges with squared distance <= D^2. The number of edges could be up to N*M = 62,500. Hopcroft-Karp can handle that quickly.
Alternatively, we could do a more clever approach like sorting edges and adding gradually, but binary search with matching each time is simpler. Since the number of distinct D^2 values is at most NM=62.5k, binary search would take log2(62.5k) ~ 16 steps. Each step runs matching, which is about O(E sqrt(V)) ~ 62500 * sqrt(500) ~ 6250022 ~ 1.4M operations, times 16 ~ 22M, fine.
Edge case: K=0? But constraint says 1≤K≤min(N,M), so at least 1.
We must output the square of required time. So we find the minimum D such that matching size >= K, then output D^2. Since we are binary searching on squared distances, we can directly find min S such that matching size >= K and output S. But careful: the time is the maximum Euclidean distance among the K pairs in the optimal assignment, which may be not exactly a distance that is present? But since we are matching based on threshold, the optimal D is the minimum threshold that allows a K-matching. This threshold corresponds to some edge distance (the K-th bottleneck) in an optimal assignment. In minmax assignment, the optimal value is equal to the smallest value such that the graph has a K-matching. This value will be one of the squared distances because if we consider any D that is not exactly a distance, we could reduce it to the next highest distance that still works? Actually we need minimal D such that there is a matching of size K. If we have a matching with max distance D0 (actual maximum among edges used). Then the graph with threshold D0 (>= that max) will have that matching. The minimal threshold S_min is the minimum value such that there is a K-matching. This value must be equal to the maximum edge weight in some K-matching; it is the min over matchings of max edge weight. That's exactly the bottleneck assignment problem. The optimal value is always one of the edge weights (since if we consider a value not equal to any edge weight, you can lower it to the next smaller edge weight if it still works, else not). So we can binary search over sorted unique edge squared distances.
Thus algorithm:
Read N, M, K.
Read biker coordinates list of N points (x_i, y_i).
Read bike coordinates list of M points (x_j, y_j).
Collect all distinct squared distances into a list, sort unique.
Or we can binary search over a range using integer low=0, high = maxDist2 (maybe up to 2*(10^7)^2 = 2e14). But it's fine because log2(2e14) ~ 48 steps, still okay. But we can combine: we can binary search on the sorted list to minimize number of checks. 48 steps is also fine. But using sorted list might be simpler: we can binary search index in sorted array of distances. But careful: we want the smallest distance S that yields matching size >= K. So we can perform binary search on the sorted array: left=0, right=len(arr)-1, while left<right: mid=(left+right)//2; if matching possible with threshold arr[mid], then right=mid; else left=mid+1. Then answer = arr[left]. But we need to ensure that matching is possible for at least one threshold (the maximum possible distance definitely works because we can match all? Actually with high threshold we can match all K, yes. So the max in the array will work, but maybe we need to consider that the threshold might need to be higher than any edge distance? Actually if we take threshold = maxDist2 (the largest distance), all edges are present, so we can certainly match at least K (since K<=min(N,M)), so there is a solution. So binary search on sorted array works.
But note: there might be many duplicate distances; we can sort unique.
Alternatively, we could use a priority queue or parametric matching. But binary search is fine.
Implementation details:
We'll store bikers on left side (size N), bikes on right side (size M).
For each check, we need to build adjacency list: for each biker i, iterate over bikes j and if dist2[i][j] <= S, add j to adj[i].
Then run Hopcroft-Karp.
Hopcroft-Karp implementation (from typical CP):
left side nodes: 0..N-1, right side: 0..M-1.
pairU array size N with -1 for unmatched, pairV array size M with -1.
dist array for BFS.
BFS: find unmatched left nodes, set dist to 0, enqueue. For others INF. Then while queue, pop u, if dist[u] < dis (but typically BFS to find augmenting paths). Standard.
But note: N and M are up to 250, but we can also use simple DFS for each node (Kuhn's algorithm) which is O(NE) ~ 25062500=15.6M per check, times ~16 = 250M, might be borderline but still maybe okay in Python? 250M operations might be too slow. So better use Hopcroft-Karp.
Implementation of Hopcroft-Karp:
def bfs():
from collections import deque
q = deque()
for u in range(N):
if pairU[u] == -1:
dist[u] = 0
q.append(u)
else:
dist[u] = INF
found = False
while q:
u = q.popleft()
for v in adj[u]:
pu = pairV[v]
if pu != -1 and dist[pu] == INF:
dist[pu] = dist[u] + 1
q.append(pu)
elif pu == -1:
found = True
return found
def dfs(u):
for v in adj[u]:
pu = pairV[v]
if pu == -1 or (dist[pu] == dist[u] + 1 and dfs(pu)):
pairU[u] = v
pairV[v] = u
return True
dist[u] = INF
return False
Then max matching = while bfs(): for each u with pairU==-1: if dfs(u): matching++.
We'll do that.
Now building adjacency each check: we can precompute all distances and store them in a list of (dist2, i, j) maybe. But for each check we need to quickly know which edges are <= S. If we binary search over sorted array and we have to build adjacency many times, we can just loop over all i,j and check condition; that's N*M = 62500 per check, times ~16 = 1M, fine.
Thus simple.
Edge Cases: There may be multiple bikers at same coordinates or bikes at same coordinates; doesn't matter.
Now we need to output the square of required time, which is our found S.
Let's test with sample:
N=3, M=3, K=2.
bikers: (0,1),(0,2),(0,3)
bikes: (100,1),(200,2),(300,3)
dist2: (0,1)-(100,1) = 100^2 =10000, (0,2)-(200,2)=200^2=40000, (0,3)-(300,3)=300^2=90000, cross distances: (0,1)-(200,2) = sqrt((200)^2+( -1?) Actually (0-200)^2 + (1-2)^2 =40000+1=40001. So many distances. The sorted distinct distances will include 10000,40000,40001,... The minimal S for K=2? Let's reason: We need match 2 bikers to 2 bikes with max distance minimized. If we match biker1 to bike1 (10000) and biker2 to bike2 (40000) -> max=40000. Could we do better? If we match biker1 to bike1 (10000) and biker3 to bike2? biker3 (0,3) to bike2 (200,2): (200)^2+(1)^2=40001, max=40001 >40000. If we match biker2 to bike1 (0,2)-(100,1): 100^2+1^2=10001, and biker1 to bike2: (0,1)-(200,2):40001, max=40001 >40000. So optimal max=40000. So answer=40000.
Our algorithm should produce 40000.
Implementation steps:
Read input.
Parse ints.
Store bikers list: list of (x,y)
Store bikes list: list of (x,y)
Compute all squared distances if we want sorted unique, or we can just binary search over integer range.
Approach A: generate list of all distances squared, sort unique.
This list length up to 62500 (since N*M=62.5k, but can be less if duplicates). Sorting is fine.
Binary search over indices of sorted list.
But need to be careful: the optimal S might be 0 if there is a bike at same location as biker? That's possible. The list will contain 0 maybe. Works.
For each candidate S, test matching.
Define function can(S):
Build adjacency: for i in range(N): adj[i]=[]
for i in range(N):
for j in range(M):
dx = bikers[i][0]-bikes[j][0]
dy = bikers[i][1]-bikes[j][1]
if dxdx+dydy <= S: adj[i].append(j)
Then run Hopcroft-Karp to compute max matching size.
Return size >= K.
Optimization: precompute distances squared matrix to avoid recomputation? We'll compute inside loop anyway. To avoid recomputing squares each time, we can precompute a matrix dist2[i][j] once and then in can(S) just compare with S. That's efficient. So we compute dist2 matrix as list of lists of ints.
Then can(S) loops over i,j, if dist2[i][j] <= S, add j.
Now Hopcroft-Karp.
Implementation details for Hopcroft-Karp with N up to 250, M up to 250. We'll need adjacency lists. BFS and DFS as described.
But we must be careful: In bfs, we need to set dist for left nodes. Standard Hopcroft-Karp:
dist = [-1]*N
Use INF sentinel.
Pseudo:
INF = 10**9
def bfs():
from collections import deque
q = deque()
for u in range(N):
if pairU[u] == -1:
dist[u] = 0
q.append(u)
else:
dist[u] = INF
found = False
while q:
u = q.popleft()
for v in adj[u]:
u2 = pairV[v]
if u2 != -1 and dist[u2] == INF:
dist[u2] = dist[u] + 1
q.append(u2)
elif u2 == -1:
found = True
return found
def dfs(u):
for v in adj[u]:
u2 = pairV[v]
if u2 == -1 or (dist[u2] == dist[u] + 1 and dfs(u2)):
pairU[u] = v
pairV[v] = u
return True
dist[u] = INF
return False
while bfs():
for u in range(N):
if pairU[u] == -1:
if dfs(u):
matching += 1
That yields max matching.
Note: In dfs, we rely on global dist and pair arrays.
Edge: It's possible that adjacency list contains many edges, but Hopcroft-Karp is efficient.
Now binary search.
We have sorted unique distances list called vals. However, we need to ensure that the answer is among them. But what if the minimal S that allows K matching is not exactly a distance? Suppose we have a situation: For threshold D, we can get matching size K, but for any smaller threshold we cannot. If D is not exactly a distance, then there is no edge with distance exactly D, but that's fine because threshold is inclusive of edges <= D. If D is between two distances, then the set of edges is exactly the same as for the next lower distance (since edges are only present at discrete distances). So if D works and is not equal to any distance, then the largest distance less than D (the maximum distance <= D that is an actual edge distance) would also work, because the set of edges is the same (since no new edges appear when increasing threshold until you cross a distance). Actually if D is not equal to any distance, let d0 = max edge distance <= D. Since D > d0, but there is no edge with distance in (d0, D], so the set of edges with threshold D is same as with threshold d0. Therefore d0 also works, contradicting minimality if D is minimal. So minimal S must be an actual edge distance. So safe.
Thus we can binary search over sorted unique distances.
Implementation details for binary search:
left = 0
right = len(vals)-1
while left < right:
mid = (left + right)//2
if can(vals[mid]):
right = mid
else:
left = mid+1
answer = vals[left]
But need to consider possibility that can(vals[-1]) might be false? But it should be true because with max distance (the largest distance) we include all edges, so matching size >= min(N,M) >= K, so true. So binary search will converge.
Complexities fine.
Now some careful points: Input may have extra spaces, lines. Use sys.stdin.read() to read all ints quickly.
Let's design code.
Potential improvements: Could also use integer binary search without generating list, but generating list is fine.
We must compute all distances squared. Since coordinates up to 1e7, squared up to 2e14, within 64-bit signed? 2*(1e7)^2 = 2e14, fits in 2^63-1 ~9e18, so fine as Python int (unbounded anyway). Use Python int.
Now implement Hopcroft-Karp carefully.
Testing with sample.
Also test with simple case: N=1, M=1, K=1, biker (0,0), bike (1,1). Distance^2=2, answer=2.
Case where multiple bikers at same spot: N=2,M=2,K=2, bikers (0,0),(0,0), bikes (1,0),(2,0). Distances: (0,0)-(1,0)=1, (0,0)-(2,0)=4. Both bikers can take either. Optimal max distance? We can assign one to 1 and one to 2 -> max=4. But maybe assign both to 1? Not possible because one bike per biker. So minmax = min over matchings of max distance: if we assign both to 1? Not possible. So the best is assign one to 1 and one to 2 -> max=4. Could we assign both to 2? That yields max=4 as well. So answer=4. But maybe we could assign one to 1 and one to 2, but we could try to assign biker1->2 and biker2->1, same. So minmax=4. Actually check if there is matching with max=2? If threshold=2, edges: distances <=2: only the bike at distance1 qualifies (1<=2) and bike at distance4 not. So only one edge, can't get matching size 2. So minimal threshold = 4. Good.
Now consider scenario where distances are not integer? But coordinates are integer, so squared distances integer.
Alright.
But the problem says "square of required time". Since time = Euclidean distance, squared time = squared distance. So output integer.
Now let's implement.
We'll use sys.stdin.buffer.read() to get all input, split into ints.
def bfs():
q = deque()
for u in range(N):
if pairU[u] == -1:
dist[u] = 0
q.append(u)
else:
dist[u] = INF
found = False
while q:
u = q.popleft()
for v in adj[u]:
pu = pairV[v]
if pu != -1 and dist[pu] == INF:
dist[pu] = dist[u] + 1
q.append(pu)
elif pu == -1:
found = True
return found
def dfs(u):
for v in adj[u]:
pu = pairV[v]
if pu == -1 or (dist[pu] == dist[u] + 1 and dfs(pu)):
pairU[u] = v
pairV[v] = u
return True
dist[u] = INF
return False
matching = 0
while bfs():
for u in range(N):
if pairU[u] == -1:
if dfs(u):
matching += 1
return matching
def can(S, dist2, N, M, K):
adj = [[] for _ in range(N)]
for i in range(N):
di = dist2[i] # list of M distances
for j in range(M):
if di[j] <= S:
adj[i].append(j)
# quick check: if any biker has no edges? Not necessary.
matching = hopcroft_karp(adj, N, M)
return matching >= K
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
if not data:
return
it = iter(data)
N = next(it); M = next(it); K = next(it)
bikers = [(next(it), next(it)) for _ in range(N)]
bikes = [(next(it), next(it)) for _ in range(M)]
code
# Precompute squared distances matrix
dist2 = [[0]*M for _ in range(N)]
for i in range(N):
x1, y1 = bikers[i]
for j in range(M):
x2, y2 = bikes[j]
dx = x1 - x2
dy = y1 - y2
dist2[i][j] = dx*dx + dy*dy
# Collect all distinct distances
vals = set()
for i in range(N):
for j in range(M):
vals.add(dist2[i][j])
vals = sorted(vals)
# binary search
lo = 0
hi = len(vals)-1
ans = vals[-1] # fallback
while lo <= hi:
mid = (lo + hi) // 2
if can(vals[mid], dist2, N, M, K):
ans = vals[mid]
hi = mid - 1
else:
lo = mid + 1
print(ans)
if name == "main":
main()
But careful: Binary search condition: we want smallest S such that can(S) true. In the while lo <= hi, we store ans when true and move hi = mid-1. That's okay.
Alternatively, we could use:
lo = 0; hi = len(vals)-1
while lo < hi:
mid = (lo+hi)//2
if can(vals[mid], dist2, N, M, K):
hi = mid
else:
lo = mid+1
ans = vals[lo]
That's more typical.
We must ensure that can(vals[mid]) is computed efficiently.
Potential issue: The number of distinct distances might be up to 62,500, so binary search about 16 steps. Good.
But note: we used set and sorted. That's fine.
Now test with sample.
Let's simulate quickly.
Edge Cases: K may be equal to N or M or both, fine.
Now we need to consider that the problem might have a different interpretation? Let's read carefully: "Jack can instruct any biker to move towards any bike in the city. In order to minimize the time to start the race, Jack instructs the bikers in such a way that the first K bikes are acquired in the minimum time. Every biker moves with a unit speed and one bike can be acquired by only one biker. A biker can proceed in any direction. Consider distance between bikes and bikers as Euclidean distance. Jack would like to know the square of required time to start the race as soon as possible."
Interpretation: The bikers move simultaneously. We want the minimum time T such that there exists a way to assign K distinct biker-bike pairs and each biker moves directly to their assigned bike (or maybe they can be instructed to change target midway? But typically they go straight). Since they all move at same speed, the time when the K-th bike is acquired is the maximum travel time among those K bikers (if they all start at same time). So we want to minimize that maximum travel time, which is the minimax assignment.
Thus correct.
One nuance: "first K bikes are acquired" could imply we care about the time when the K-th acquisition happens, not necessarily the maximum of assigned distances if we can have bikers wait? But they all start moving at time 0; acquisitions happen at times equal to distances. The K-th acquisition (in chronological order) might be less than the maximum if some bikers arrive earlier? Actually the time when the K-th bike is acquired is the K-th smallest arrival time among the bikers? Wait, "first K bikes are acquired" - if we have more than K bikers, only K need to get bikes. The others we can ignore. They want to start the race as soon as possible when K bikes have been acquired. So we can choose any K bikers to assign to K bikes. The time when the race can start is the time when the last of those K bikers reaches his bike (since all K need to have acquired bikes). However, suppose we assign bikers with distances d1,d2,...,dK sorted. They all start moving at time 0 and each travels straight. They will arrive at times d1,...,dK. The race can start only after all K have arrived, i.e., at time max(d_i). If we could choose a set of K bikers and assign them to K bikes arbitrarily, we want to minimize the maximum distance among assigned pairs. That is classic bottleneck assignment.
Thus our interpretation is correct.
Now, consider that bikers could potentially not go directly to a bike but maybe they could intercept? But they move with unit speed, so shortest path to a bike is straight line; any other path would take longer, so not beneficial.
Thus solution stands.
Now about constraints: N and M up to 250. Could we use a more efficient algorithm like Hungarian for bottleneck? But binary search with matching is fine.
Now about Hopcroft-Karp: We need to ensure that recursion depth in DFS is not too high. N is only 250, so recursion depth of DFS could be up to maybe matching length, which is at most 250, fine. But Python recursion might be okay, but we can implement DFS iteratively or use sys.setrecursionlimit. Let's set recursion limit to 10000 to be safe.
But our DFS uses recursion: inside dfs(u) calls dfs(pu). The depth could be up to the length of augmenting path, which is at most O(N+M). That's up to 500, so safe but we'll set recursion limit just in case.
Alternatively, we could implement DFS with stack, but recursion is simpler.
We'll add at top: sys.setrecursionlimit(10000)
Now test with sample manually (simulate in head). Should output 40000.
Now consider a case where distances are equal: e.g., N=2, M=2, K=2, bikers at (0,0), (0,0), bikes at (0,0), (0,0). Then all distances 0. So can(0) should have matching size? dist2 <= 0, edges present for all pairs (since 0 <= 0). So adjacency: each biker connected to both bikes. Hopcroft-Karp should find matching size 2. So ans=0. Good.
Now what about negative distances? Not possible.
Now, maybe we should be careful about input formatting: the sample input includes line breaks and spaces. Our reading via split handles that.
Now, complexity: In each can() we build adjacency list, which is O(N*M) = 62.5k, and then Hopcroft-Karp O(E sqrt(V)) ~ 62.5k * sqrt(500) ~ 1.4M. Times at most 16 = ~22M, plus overhead, Python should handle within time. Typically 1 sec maybe borderline but likely okay given constraints 250. However, we can optimize by not building adjacency from scratch each time; we could sort edges by distance and gradually add edges while binary searching? But we are doing binary search, so building adjacency each time is simpler. 22M operations is fine in Python, but need to be careful with constant factors. However, each can call also does BFS/DFS loops, which involve Python loops over adjacency. Still likely okay. But we can further improve by precomputing all edges sorted and then using a union-of-frozens? Actually we can use a two-pointer technique: while binary searching, we could reuse adjacency but it's messy.
Alternative: we could directly use Hungarian or min-cost max-flow? Not needed.
I think it's fine.
One more consideration: The problem may be from HackerRank or similar, with multiple test cases? The description doesn't mention multiple test cases, so it's a single test.
Thus solution is ready.
Now, to be thorough, let's test edge: N=250, M=250, K=250, all bikers at (0,0), all bikes at (10^7,10^7). Distance squared = 2*(10^7)^2 = 2e14. So the threshold S must be at least that. Our binary search over sorted distinct distances will have only one distance (2e14). can(2e14) will have all edges, matching size = 250, true. So answer is that.
Now, what if there are many distinct distances? Up to 62,500, binary search 16 steps.
Now, the set conversion and sorting is O(NM log NM) = 62.5k log 62.5k ~ 62.5k * 16 = 1M, fine.
Potential memory: set of up to 62.5k ints.
Now, let's also think about alternative interpretation: Could it be that we are allowed to assign multiple bikers to the same bike? The problem says "one bike can be acquired by only one biker." So no.
Thus done.
But wait, the problem says "the first K bikes are acquired in the minimum time." Could it be that they care about the sum of times? No, "minimum time" suggests the time when the K-th bike is acquired (the moment the race can start). That is the maximum of the times of those K bikers if they all start at same time, but maybe if we can decide which biker goes to which bike and they can start moving at different times? Usually they all start at time zero. So it's max.
So our solution stands.
Now, we should also consider that we could have bikers not assigned to any bike, and they may move to any bike but we only care about the K that acquire bikes first. Could we have a scenario where a biker goes to a bike that is farther, but because they start later? No, they all start at time 0.
Thus, it's exactly the bottleneck assignment.
Now, we can implement.
But we need to be careful: In can(S), we need to compute matching size quickly. But we might also early exit if it's impossible to reach K: e.g., if any biker can't reach any bike? But we need at least K edges total? Not necessary; but we can compute a quick bound: if number of bikers or bikes less than K, but K <= min(N,M) so it's fine.
But maybe we can prune: For each biker, if no bike within distance S, then they cannot be used, but still other bikers might be enough. So no simple bound.
Now, we must ensure that Hopcroft-Karp runs fast. Let's code efficiently:
Use list of lists for adjacency.
Use deque for BFS.
Use recursion for DFS, but set recursion limit.
Or we can implement DFS iteratively? Not needed.
One more optimization: In can(S), we can pre-filter: if a biker has degree 0, we can ignore; but that's automatically handled.
Potential bug: The adjacency list building inside can(S) for each S may allocate many small lists. That's okay.
But maybe we can avoid building adjacency from scratch each time by precomputing sorted list of edges per biker and then using while loops? But fine.
Now, we need to test with random cases to ensure correct.
Let's consider a small case: N=2, M=2, K=2, bikers: (0,0), (10,0); bikes: (0,10), (10,10). Distances: b1->bike1: sqrt(0^2+10^2)=10, b1->bike2: sqrt(10^2+10^2)=~14.14; b2->bike1: sqrt(10^2+10^2)=~14.14; b2->bike2: 10. So squared distances: 100, 200, 200, 100. The optimal minmax assignment: assign b1 to bike1 (100), b2 to bike2 (100) -> max=100. So answer=100. Check: can(100) edges: distances <=100: only the two 100 edges. So adjacency: b1 connected to bike1, b2 connected to bike2. Matching size 2 -> true. can(99) edges: none? Actually 99 <100, no edges, matching=0 -> false. So answer=100.
Works.
Now, consider case where need to choose which K bikers to use. For example N=3, M=3, K=2. Bikers: (0,0), (0,10), (0,20). Bikes: (5,0), (5,20), (5,30). Distances: b1-b1:5, b1-b2: sqrt(5^2+20^2)= sqrt(25+400)= sqrt425≈20.6, b1-b3: sqrt(5^2+30^2)= sqrt(925)≈30.4; b2-b1: sqrt(5^2+10^2)= sqrt125≈11.18, b2-b2: sqrt(5^2+10^2? Actually b2 (0,10) to bike2 (5,20): dx5, dy10 => sqrt(25+100)= sqrt125≈11.18, b2-b3: sqrt(5^2+20^2)= sqrt425≈20.6; b3-b1: sqrt(5^2+20^2)=20.6, b3-b2: sqrt(5^2+10^2)=11.18, b3-b3: sqrt(5^2+10^2? Actually (0,20)-(5,30):5,10 => sqrt125≈11.18. So many distances. The optimal two assignments to minimize max distance: Possibly assign b1 to bike1 (5) and b3 to bike2 (11.18) -> max 11.18. Or b1 to bike1 (5) and b2 to bike2 (11.18) -> max 11.18. So answer squared = 125? Since 11.18^2=125. So min S=125. Let's see if our algorithm yields that: distances squared: 25, 425, 925, 125, 425, 125, 425, 125, 125? Let's list all:
b1: (0,0): to bike1(5,0): (5)^2+0=25
to bike2(5,20): 25+400=425
to bike3(5,30): 25+900=925
b2: (0,10): to bike1(5,0): 25+100=125
to bike2(5,20): 25+100=125? Wait (0,10)-(5,20): dx=5, dy=-10 => 25+100=125
to bike3(5,30): 25+400=425
b3: (0,20): to bike1(5,0): 25+400=425
to bike2(5,20): 25+0=25? Actually (0,20)-(5,20): dx=5, dy=0 => 25
to bike3(5,30): 25+100=125
Wait check: b3 to bike2: (0,20)-(5,20): dx=5, dy=0 -> 25. So b3 to bike2 is 25. So we have many 25 distances. Actually b3 to bike2 is 25, and b1 to bike1 is 25, b3 to bike? Also b3 to bike? b2 to bike? Let's recalc all squared distances systematically:
So we have distances: 25,425,925,125,125,425,425,25,125. So the set includes 25,125,425,925.
Now we need K=2. Is it possible to get max distance 25? That would require both selected pairs having distance <=25. Edges with <=25: only the pairs with distance 25: AX (25), CY (25). That's two edges but they involve bikers A and C, and bikes X and Y. They are distinct bikers and distinct bikes, so we can match A->X and C->Y. That's a matching of size 2 with max distance 25. So answer would be 25, not 125. Indeed we can match A to X (25) and C to Y (25). So min max = 25. So answer 25. Good. So our algorithm would find can(25) true -> ans=25.
Thus correct.
Now we should ensure that the matching algorithm finds a matching of size K=2 with edges AX and CY. That's fine.
Now, implementation details: For binary search over sorted unique values, we need to be careful: can(25) must be true. And can(24) would be false because no edges. So answer=25.
Now, we must also consider that we need to output square of required time, which is integer. In this case, 25.
Now, code ready.
Potential improvements: Since N and M are up to 250, we could also use Hungarian algorithm for the bottleneck assignment directly: sort all edges, then use binary search with matching. So our approach is good.
Now, verify that Hopcroft-Karp returns maximum matching. We'll test with some cases.
Edge case: When K is less than min(N,M), we only need matching size K, not necessarily maximum matching. But our can(S) checks if max matching >= K. That's correct. Because we need to see if there exists a matching of size at least K. So we can compute the maximum matching and compare to K. However, we can early exit once we have found K matches to save time. In Hopcroft-Karp, we compute full maximum matching, but we could break if we reach K. However, implementing early break might complicate. But it's fine to compute full matching; it's still O(E sqrt(V)).
But we can micro-opt: if K is small, maybe we can do something else, but it's okay.
Now, memory: dist2 matrix: we can compute as list of lists of ints.
Now, for binary search over integer range rather than sorted list might be simpler and avoid building set and sorting. Since coordinates up to 1e7, max squared distance is about 2*(1e7)^2 = 2e14. Binary search over [0, 2e14] would take about log2(2e14) ~ 48 steps. That's 48 matching computations, which might be okay too. But 48 * matching ~ 48 * 1.4M = 67M operations, still fine. But we need to be careful about time limits if many test cases (but only one). So either approach works. I'll go with sorted unique list to reduce steps to ~16, but it also requires building set and sorting. Not a big deal.
But there is a nuance: the answer may not be among the distances? As argued, it is. So we can binary search on sorted list.
However, there is a subtlety: Suppose we have multiple edges with same distance, we include them. Good.
Now, one more nuance: The matching must be between distinct bikers and distinct bikes. Our algorithm ensures that.
Now, we must ensure we treat bikers and bikes as distinct sets.
Now, let's implement.
But wait, we need to be careful about indexing and recursion depth for DFS in Hopcroft-Karp. I'll implement DFS recursively as typical.
But there is a known issue: Python recursion can be slow for many calls, but depth <= 250, and number of calls per DFS maybe up to number of edges. It's fine.
We'll set recursionlimit to maybe 10000.
Now, code:
import sys
from collections import deque
def hopcroft_karp(adj, n, m):
INF = 10**9
pair_u = [-1] * n
pair_v = [-1] * m
dist = [0] * n
code
def bfs():
q = deque()
for u in range(n):
if pair_u[u] == -1:
dist[u] = 0
q.append(u)
else:
dist[u] = INF
found = False
while q:
u = q.popleft()
for v in adj[u]:
pu = pair_v[v]
if pu != -1 and dist[pu] == INF:
dist[pu] = dist[u] + 1
q.append(pu)
elif pu == -1:
found = True
return found
def dfs(u):
for v in adj[u]:
pu = pair_v[v]
if pu == -1 or (dist[pu] == dist[u] + 1 and dfs(pu)):
pair_u[u] = v
pair_v[v] = u
return True
dist[u] = INF
return False
matching = 0
while bfs():
for u in range(n):
if pair_u[u] == -1:
if dfs(u):
matching += 1
return matching
def can(S, dist2, N, M, K):
adj = [[] for _ in range(N)]
for i in range(N):
row = dist2[i]
# We could preallocate list and extend, but simple loop.
# For j in range(M):
# if row[j] <= S: adj[i].append(j)
# Using list comprehension maybe faster:
# but simple loop okay.
for j in range(M):
if row[j] <= S:
adj[i].append(j)
# Compute max matching
match = hopcroft_karp(adj, N, M)
return match >= K
def main():
import sys
sys.setrecursionlimit(10000)
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))
bikers = [(int(next(it)), int(next(it))) for _ in range(N)]
bikes = [(int(next(it)), int(next(it))) for _ in range(M)]
code
# Compute distance matrix
dist2 = [[0]*M for _ in range(N)]
for i in range(N):
x1, y1 = bikers[i]
for j in range(M):
x2, y2 = bikes[j]
dx = x1 - x2
dy = y1 - y2
dist2[i][j] = dx*dx + dy*dy
# Get sorted unique distances
vals = set()
for i in range(N):
for j in range(M):
vals.add(dist2[i][j])
vals = sorted(vals)
# binary search
lo = 0
hi = len(vals) - 1
ans = vals[-1]
while lo <= hi:
mid = (lo + hi) // 2
if can(vals[mid], dist2, N, M, K):
ans = vals[mid]
hi = mid - 1
else:
lo = mid + 1
print(ans)
if name == "main":
main()
But we need to ensure that when we binary search, we use while lo <= hi and store ans. The above will produce correct ans.
Alternatively, we can use:
lo, hi = 0, len(vals)-1
while lo < hi:
mid = (lo+hi)//2
if can(vals[mid], dist2, N, M, K):
hi = mid
else:
lo = mid+1
ans = vals[lo]
But careful: can(vals[mid]) might be false for all? But last value should be true. So this works.
We'll use while lo<hi style.
Let's adopt:
lo = 0
hi = len(vals)-1
while lo < hi:
mid = (lo+hi)//2
if can(vals[mid], dist2, N, M, K):
hi = mid
else:
lo = mid+1
ans = vals[lo]
print(ans)
Now test with sample.
We should test with some random cases to ensure correctness.
But we must also consider that the number of distinct distances might be large but still manageable.
Potential improvements: Instead of building set and sorting, we could directly collect all distances into a list, sort it, then binary search. But using set eliminates duplicates and reduces binary search steps? Not necessary but fine.
However, note: For binary search on sorted list of distances, we need to ensure that the answer is in the list. But as argued, it is. So fine.
Now, test with simple cases using code mentally.
Case: N=1, M=1, K=1, biker (0,0), bike (3,4). dist2=25. vals=[25]. lo=0, hi=0, loop not entered, ans=25. print 25. correct.
Case: N=2, M=2, K=2, bikers (0,0),(0,0), bikes (0,0),(1,0). dist2: (0,0):0,1; (0,0):0,1. vals = {0,1}. Sorted [0,1]. Check can(0)? adjacency: edges with dist2<=0: only exact zero: both bikers to bike1? Actually both distances to bike1 (0,0) are 0, to bike2 (1,0) distance^2=1. So at threshold 0, edges: each biker only connected to bike1 (since bike1 distance 0). So adjacency: each biker has one edge to bike1. Max matching? We can match at most 1 (since only one bike1). So matching size=1 <2. So can(0) false. Then lo becomes 1? Let's trace: lo=0, hi=1. mid=0, can(0) false => lo=1. Now lo=1, hi=1, exit loop. ans=vals[1]=1. So answer 1. That corresponds to max distance 1 (since we have to assign one biker to bike2, distance 1). Correct.
Now, case where multiple distances same, answer is that distance.
Now, check performance: building adjacency each can call loops over N*M (62500). For each edge, we do a conditional and possibly append. Append is O(1) amortized. So 62500 * 16 ~ 1M appends. That's fine.
Hopcroft-Karp: In worst case, each BFS/DFS processes all edges. For each BFS, we iterate over all u and their adjacency. The number of BFS phases is at most O(sqrt(V))? Actually Hopcroft-Karp runs in O(sqrt(V)*E) in theory, but in practice for small graphs it's okay. For N=M=250, sqrt(500) ~ 22. So up to 22 BFS phases. Each BFS and DFS collectively visit edges. So total operations maybe a few million per can.
Thus total maybe 16 * (building adj + matching) ~ 16 * (62.5k + few million) ~ maybe 50 million operations. In Python, this might be borderline but likely acceptable if optimized. However, we might need to be more efficient. We can possibly reduce the number of can calls by using binary search on sorted distances (only ~16 calls). That is manageable.
We can also early exit from matching if we already have size >= K during DFS augmentations: In Hopcroft-Karp, we can check after each successful augmentation if matching >= K and return early. This can cut time when K is small. Let's add that optimization: In the while bfs loop, after each dfs that returns True, we increment matching and if matching >= K, we can return True early. But careful: we must still complete the BFS phase? Actually we can break out of the outer loop and return True. That's fine because we only need to know if matching size >= K, not the full maximum. So we can modify hopcroft_karp to return as soon as matching reaches K.
But note: In Hopcroft-Karp, the BFS phase finds many augmenting paths, and we try to augment for each free u. If we get matching >= K during that, we can return True. This can significantly speed up when K is small relative to N,M. So let's implement a version that stops when matching >= K.
We'll define function can(S) that builds adjacency and then runs a matching that returns True as soon as we have K matches.
Modify hopcroft_karp to accept K and stop early.
Implementation:
def max_matching_at_least_K(adj, N, M, K):
pairU = [-1]*N
pairV = [-1]*M
dist = [0]*N
INF = 10**9
matching = 0
code
def bfs():
from collections import deque
q = deque()
for u in range(N):
if pairU[u] == -1:
dist[u] = 0
q.append(u)
else:
dist[u] = INF
found = False
while q:
u = q.popleft()
for v in adj[u]:
pu = pairV[v]
if pu != -1 and dist[pu] == INF:
dist[pu] = dist[u] + 1
q.append(pu)
elif pu == -1:
found = True
return found
def dfs(u):
for v in adj[u]:
pu = pairV[v]
if pu == -1 or (dist[pu] == dist[u] + 1 and dfs(pu)):
pairU[u] = v
pairV[v] = u
return True
dist[u] = INF
return False
while bfs():
for u in range(N):
if pairU[u] == -1:
if dfs(u):
matching += 1
if matching >= K:
return True
return matching >= K
Now can(S) simply calls this.
But note: In this version, we are using recursion for dfs, but it's fine.
We'll also need to import deque inside bfs to avoid global lookup? We'll import at top.
Now, we must be careful: In the for u loop, we may augment many times per BFS. If we break after reaching K, we might not complete the BFS for remaining u but that's okay.
Now, the while loop condition: bfs returns True if there is at least one free vertex on right reachable. But if we exit early due to matching>=K, we can return True.
Now, also we might need to consider that after BFS, there might be multiple augmenting paths; we process them. If we reach K, stop.
Now, we also might want to early prune: if total possible edges < K (i.e., sum of degrees of bikers? Not trivial). Not needed.
Now, can we further optimize building adjacency each time? Possibly we can pre-sort edges per biker? But fine.
Now, we should also note that using Python lists for adjacency and building them each time might be okay. However, we can also precompute all edges sorted and then for each S, we could use a bitset or incremental, but not necessary.
Now, let's consider the time complexity: In worst case K = min(N,M) = 250, so we need full matching anyway. But that's okay.
Now, let's think about worst-case scenario: N=250, M=250, all distances distinct and sorted increasing. We binary search ~16 times. Each can builds adjacency of up to 62.5k edges. The matching algorithm then will try to find up to 250 matches. Hopcroft-Karp does BFS/DFS. Each BFS visits all edges, each DFS also visits edges. In dense graph, Hopcroft-Karp can run in O(E * sqrt(V)) ~ 62.5k * 22 = 1.4M operations per can. 16 * 1.4M = 22.4M. Plus adjacency building 16*62.5k=1M. So total ~23.4M operations. In Python, 23 million simple operations should be okay within a second or two? But BFS/DFS involves loops over adjacency, Python overhead might be somewhat high but still likely within typical time limits (maybe 2-3 seconds). But we need to be cautious: The problem might be from HackerEarth or Codeforces, typical time limit 1-2 seconds. 23M operations might be okay if implemented efficiently, but Python might be a bit slow if not optimized. However, we can further reduce steps: Since we binary search on sorted unique distances, steps ~ log2(62500) ~ 16, as said. That's okay.
We could also reduce the number of can calls by using a "selection" method like using a priority queue to find the K-th smallest edge in a min-cost flow? But not needed.
Another approach: Since N and M are only 250, we could also use Hungarian algorithm variant for bottleneck assignment: sort all edges, then use union-find to check if there is a perfect matching? Actually there is a known algorithm for bottleneck assignment: sort edges by weight, then add edges one by one until the bipartite graph has a matching of size K. That would be like using a DSU? But matching is not monotonic with edge addition; we can use binary search or incremental matching. Incremental matching: we could sort all edges (dist2) and then add edges gradually, maintaining a matching using Hopcroft-Karp incremental? Not trivial. But we could sort edges and for each new edge, try to augment matching. Since we only need to know when matching size reaches K, we could just sort edges and then run incremental matching: start with empty graph, add edges in increasing order, after each addition, run augmenting paths for the new edge (or recompute matching). However, we would need to maintain matching incrementally. Standard approach: sort edges, then for each edge in order, add it to graph and try to find augmenting path using DFS from the new edge's left node if it's not already matched? That could be done by a simple DFS augment (like Kuhn's algorithm) for each edge addition. Since each addition could trigger an augment that may shuffle matches. In Kuhn's algorithm, each augment takes O(E) worst-case. If we add all edges (62.5k) and after each addition we try to augment, that could be O(E^2) which is too high. But we can stop once we reach K. In the worst case we might need to add many edges. That could be similar to binary search complexity but maybe slower.
Binary search with full matching each time might be simpler.
We can also consider using a "binary search on answer and use max flow with Dinic" but Hopcroft-Karp is fine.
Now, micro-optimizations:
Use local variables inside functions to avoid global lookups.
In can(S), we can pre-create adj as list of lists; we can allocate a list of N empty lists and then for each i, we can do: adj[i] = [j for j, d in enumerate(dist2[i]) if d <= S] using list comprehension which is faster than manual loop with append. Let's test: list comprehension iterates over row and condition. That may be faster because it's implemented in C. So we'll use that.
So:
adj = [ [j for j, d in enumerate(dist2[i]) if d <= S] for i in range(N) ]
This builds adjacency in one line and may be faster.
Now, for matching, we can also pre-import deque and use local references.
We'll also move the bfs and dfs definitions inside the matching function to capture adj, pairU, etc. Or we can define them as nested functions to capture closure variables; that's fine.
Now, we need to be careful about recursion depth: In dfs, recursion depth can be up to the length of augmenting path, which is at most 2*min(N,M) maybe ~500. So recursion limit 10000 is safe.
Now, possible improvements: Use iterative DFS to avoid recursion overhead, but recursion overhead for 500 depth is not huge.
Now, let's test with sample.
I'll write the code accordingly.
One more nuance: The problem might be from an old contest and require output as integer; correct.
Now, final code.
But before finalizing, consider a potential issue: The graph is bipartite, but Hopcroft-Karp typically expects left and right partitions. In our case, left size N, right size M.
Now, there is an alternative: Since we only need to check if there is a matching of size K, we could also use a maximum flow algorithm with source to bikers (capacity 1), bikers to bikes (capacity 1 if dist2 <= S), bikes to sink (capacity 1). And then run Dinic. But Hopcroft-Karp is simpler.
Now, what about multiple test cases? The problem doesn't mention multiple test cases, so assume single.
Thus final solution is ready.
Let's produce final answer with explanation.
But wait: In the problem statement, "first K bikes are acquired" could also be interpreted differently: The bikers start moving simultaneously, and we can assign each biker to a bike, but we care about the time when the K-th bike is acquired, i.e., the K-th smallest arrival time among the bikers? Because "first K bikes are acquired" might mean the time at which the K-th bike gets occupied, not necessarily that all K bikers have arrived? Actually if we have more than K bikers, we might only need K bikes to be acquired. The race can start as soon as K bikes are acquired. That might be when the K-th bike is reached by some biker, not necessarily the same set of bikers? But we can assign any bikers to any bikes, but we only care about the time the K-th acquisition happens, which could be earlier than the maximum of the K distances if we can have some bikers arriving later but we don't need them? Wait: If we need K bikes to be acquired, we don't necessarily need all bikers to have acquired bikes; we just need that K bikes become occupied. That means we can send bikers to bikes, and the moment the K-th bike is reached by any biker, the race can start. But if we have more than K bikers, we might not care about the remaining bikers. However, the problem says: "There are N bikers present in a city having M bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only K bikers can be accommodated in the race." This suggests that we need exactly K bikers