ปัญหา
มี preferences รายการความชอบเพื่อน (index น้อย = ชอบมาก) และ pairs คู่เพื่อน เพื่อน x ไมพอใจถ้า: x คู่กับ y แต่มี u คู่กับ v ที่ x ชอบ u กว่า y และ u ชอบ x กว่า v หาจำนวนเพื่อนไม่พอใจ
ตัวอย่าง
preferences=[[1,2,3],[3,2,0],[3,1,0],[1,2,0]], pairs=[[0,1],[2,3]] → 2 (เพื่อน 1 และ 3 ไมพอใจ)
ขั้นตอนการแก้ปัญหา
graph := defaultdict(dict)- สำหรับ
(start, end)ในpairs:- สำหรับ
prefในpreferences[start]จนกว่าจะเจอend:graph[start][pref] = 1 - สำหรับ
prefในpreferences[end]จนกว่าจะเจอstart:graph[end][pref] = 1
- สำหรับ
unhappy := 0- สำหรับ
(start, end)ในpairs:- ถ้า
graph[pref].get(start)สำหรับprefในgraph[start]:unhappy += 1 - ถ้า
graph[pref].get(end)สำหรับprefในgraph[end]:unhappy += 1
- ถ้า
- คืน
unhappy
การนำไปใช้งาน (Python)
from collections import defaultdict
def solve(preferences, pairs):
graph = defaultdict(dict)
for start, end in pairs:
for pref in preferences[start]:
if pref == end:
break
graph[start][pref] = 1
for pref in preferences[end]:
if pref == start:
break
graph[end][pref] = 1
unhappy = 0
for start, end in pairs:
for pref in graph[start]:
if graph[pref].get(start, None):
unhappy += 1
break
for pref in graph[end]:
if graph[pref].get(end, None):
unhappy += 1
break
return unhappy
preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]]
pairs = [[0, 1], [2, 3]]
print(solve(preferences, pairs))
อินพุต
[[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], [[0, 1], [2, 3]]
เอาต์พุต
2