想想pidgeonhole。這種方法在所有情況下都是O(m + n)複雜度。
將每個「交易」合併爲一組規則,然後遍歷項目,將它們添加到每個滿足其規則的pidgeonhole。
然後循環處理,從物品中拉出物品(如果物品在物品中)。
例子:
"blue car", "red car", "yellow expensive car", "red expensive car", "cheap car"
的交易:
buy a red car, get a blue car for free
buy an expensive car, get a cheap car for free
的 「規則」,我們可以推斷出:
is_red, is_expensive, is_blue, is_cheap
因此,我們有2個孔,is_red和is_expensive。通過項目環,把它們添加到其規則,他們滿足所有的孔,導致這些漏洞:
is_red ("red car", "red expensive car")
is_expensive ("red expensive car", yellow expensive car")
is_blue ("blue car")
is_cheap ("cheap car")
然後通過交易循環:
buy a red car, get a blue car for free
is_red contains "red car", is_blue contains "blue car", so:
pop them from the holes and make them a deal
下一筆交易:
buy an expensive car, get a cheap car for free
is_expensive doesn't contain any cars
太酷了!謝謝 :) – Drew 2012-03-12 16:30:17