Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การรวมเซลล์ (Cell Fusion) ใน Python

ภาพรวม

โจทย์จำลองการรวมเซลล์: ในแต่ละรอบ ให้นำเซลล์ 2 ตัวที่ใหญ่ที่สุดมา interact

  • ถ้าเท่ากัน → ทั้งคู่ตาย (หายไป)
  • ถ้าไม่เท่ากัน → รวมกันเป็นเซลล์ใหม่ขนาด floor((a+b)/3)

ทำซ้ำจนเหลือ 0 หรือ 1 เซลล์ คืนขนาดเซลล์สุดท้าย หรือ -1 ถ้าไม่เหลือ

ตัวอย่าง

อินพุต: [20, 40, 40, 30]

  1. 40, 40 เท่ากัน → ตายทั้งคู่ เหลือ [20, 30]
  2. 20, 30 → floor((20+30)/3) = floor(50/3) = 16
  3. เหลือ [16] → คืน 16

โค้ด Python (ใช้ Heap/Max-Heap)

from heapq import heapify, heappop, heappush

class Solution:
    def solve(self, cells):
        cells = [-x for x in cells]  # แปลงเป็น max-heap (heapq เป็น min-heap)
        heapify(cells)
        while len(cells) > 1:
            first, second = -heappop(cells), -heappop(cells)
            if first != second:
                heappush(cells, -((first + second) // 3))
        return -cells[0] if cells else -1

ob = Solution()
cells = [20, 40, 40, 30]
print(ob.solve(cells))

ทำไมต้องใช้ค่าลบ?

Python heapq เป็น min-heap (ค่าน้อยสุดอยู่บน) ใช้ค่าลบเพื่อกลับเป็น max-heap

ผลลัพธ์

16