ปัญหา
มี m บ้าน ต้องทาสี n สี (1..n) บางหลังทาแล้ว (0 = ยังไม่ทา) บ้านที่ติดกันและสีเหมือนกันเรียกว่า "neighborhood" มี cost[i][j] = ต้นทุนทาบ้าน i สี j+1 หาต้นทุนน้อยที่สุดเพื่อให้มี neighborhood ทั้งหมด target ชุด ถ้าไม่ได้คืน -1
ตัวอย่าง
houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], n=2, target=3 → ผลลัพธ์ 11 (ทาเป็น [2,2,1,2,2] มี 3 neighborhoods: {2,2},{1},{2,2} ต้นทุน 10+1=11)
ขั้นตอนการแก้ปัญหา
m := len(houses)- ฟังก์ชัน
helper(i, p_col, grp):- ถ้า
i == m: คืน 0 ถ้าgrp == targetมิฉะนั้น inf - ถ้า
houses[i] != 0: คืนhelper(i+1, houses[i], grp + (p_col != houses[i])) total := inf- วน
col1 ถึง n:total = min(total, cost[i][col-1] + helper(i+1, col, grp + (p_col != col)))
- คืน
total
- ถ้า
ans := helper(0, -1, 0), คืนansถ้าไม่ใช่ inf มิฉะนั้น -1
การนำไปใช้งาน (Python)
def solve(houses, cost, n, target):
m = len(houses)
def helper(i, p_col, grp):
if i == m:
return 0 if grp == target else float('inf')
if houses[i] != 0:
return helper(i + 1, houses[i], grp + int(p_col != houses[i]))
total = float('inf')
for col in range(1, n + 1):
total = min(total, cost[i][col - 1] + helper(i + 1, col, grp + int(p_col != col)))
return total
ans = helper(0, -1, 0)
return ans if ans != float('inf') else -1
houses = [0,2,1,2,0]
cost = [[1,10],[10,1],[10,1],[1,10],[5,1]]
n = 2
target = 3
print(solve(houses, cost, n, target))
อินพุต
[0,2,1,2,0], [[1,10],[10,1],[10,1],[1,10],[5,1]], 2, 3
เอาต์พุต
11