1
# Runtime: 104 ms (Top 82.18%) | Memory: 13.9 MB (Top 66.34%)3
from collections import defaultdict7
def maxCompatibilitySum(8
self, students: List[List[int]], mentors: List[List[int]]10
m, n = len(students), len(students[0])12
def hamming(student, mentor):13
return sum([int(student[i] != mentor[i]) for i in range(n)])17
] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status)18
optimal = defaultdict(lambda: float("inf"))21
cost, i, mentor_status = heapq.heappop(pq) # O(logV)23
# early stopping with termination condition27
# generate successors. The next student to be assigned is at index i28
for j, mentor in enumerate(mentors): # O(m)29
if mentor_status[j] != "1":30
new_cost = cost + hamming(students[i], mentor)31
new_mentor_status = mentor_status[:j] + "1" + mentor_status[j + 1 :]33
# update optimal cost if a new successor appears with lower cost to the same node34
if new_cost < optimal[(i + 1, new_mentor_status)]:35
optimal[(i + 1, new_mentor_status)] = new_cost37
pq, (new_cost, i + 1, new_mentor_status)