有兩個n長度陣列(a
和b
)由整數> 2.查找兩個陣列
在每一個的元素轉我想從每個陣列中移除的整數有效組合的最大數量(a[i]
和b[j]
),因爲關於它們的某些條件是真的(例如它們不是共素)。 (如果條件不成立,我會嘗試刪除另一個組合)
畢竟我想找到我能達到的最大圈數(直到沒有可能的組合去除符合條件的組合) 。我們稱之爲最佳轉數。
我嘗試與搜索算法來解決這個和PriorityQueue
使用Python:
def search(n, a, b):
q = queue.PriorityQueue()
encountered = set()
encountered.add((tuple(a), tuple(b)))
q.put((number_of_coprime_combinations(a, b), a, b))
while q:
cost, a, b = q.get()
combs = not_coprime_combinations(a, b)
if not combs:
return n - len(a)
for a, b in combs:
if not (tuple(a), tuple(b)) in encountered:
q.put((number_of_coprime_combinations(a, b), a, b))
encountered.add((tuple(a), tuple(b)))
number_of_coprime_combinations(a, b)
返回的給定陣列a
和b
可能互質組合的數量。這被用作兩個數組的給定狀態的代價。
def number_of_coprime_combinations(a, b):
n = 0
for idx_a, x in enumerate(a):
for idx_b, y in enumerate(b):
if is_coprime(x, y):
n += 1
return n
not_coprime_combinations(a, b)
返回可能的狀態,其中不互質數組合已從a
和b
刪除列表:
def not_coprime_combinations(a, b):
l = []
for idx_a, x in enumerate(a):
for idx_b, y in enumerate(b):
if not is_coprime(x, y):
u, v = a[:], b[:]
del(u[idx_a])
del(v[idx_b])
l.append((u, v))
return l
>>> not_coprime_combinations([2,3],[5,6])
[([3], [5]), ([2], [5])]
的問題是,這種解決方案是針對大型陣列非常低效大整數。所以,我想知道是否有任何更好的解決這個問題..
例:
n = 4
a = [2, 5, 6, 7]
b = [4, 9, 10, 12]
人們可以刪除:
(2, 4)
(5, 10)
(6, 9)
這將導致最佳的解決方案:
a = [7]
b = [12]
但是,如果有人會刪除:
(6, 12)
(2, 10)
人會得到次優解:
a = [5, 7]
b = [4, 9]
的算法應該總是向上拐彎的最佳數量(本例中3)。
請包含函數'number_of_coprime_combinations'和'not_coprime_combinations'的代碼。另外 - 提供一組樣本數據和「結果」應該是什麼。 –
[雙圖中的最大配對](https://en.wikipedia.org/wiki/Matching_(graph_theory)#Maximum_matchings_in_bipartite_graphs) –
@InbarRose fixed;) – leezu