给定一份食谱列表和自有食材列表,哪种算法最适合确定 "Which ingredient could I add to access the most recipes?"

Given a list of recipes a list of owned ingredients, which algorithm is best to determine "Which ingredient could I add to access the most recipes?"

我希望长标题能很好地解释问题。这感觉像是一个名义上的问题,所以我怀疑有一个已知的算法,或者它可能映射到 NP。

给定一本形式为

的食谱
cookbook = {
    recipe1: [ingredient1, ingredient2, ingredient35],
    recipe2: [ingredient1, ingredient8, ingredient12], 
    recipe3: [ingredient10, ingredient22, ingredient35],
    ...
}

以及表格中的成分列表

ingredients = {
    ingredient1: true, //owned
    ingredient2: false, //unowned
    ingredient3: true,
    ...
}

哪种算法可以有效地回答“您可以添加哪种成分来完成最多的食谱?”

假设

伪代码

bestIngredient = 0
bestCount = 0
Loop I  over owned ingredients
   count = 0
   Loop R over recipes
       If I completes R
          increment count
   if count > bestCount
      bestCount = count
      bestIngredient = I

当添加成分 I 时:

Loop R over recipies
    If R needs I 
    Add I to R
score = empty hashmap
for each R in recipes
  missing = empty list
  for each I in R
    if ingredients[i] = false
      missing += I
  if size(missing) = 1
    I = missing[0]
    score[I]++
result = choose key I in score with maximum value

根据食谱创建一个 trie。对于每个查询,递归查询的子序列和一个允许的通配符,遍历 trie。 (食谱和查询都应该以相同的方式对成分进行排序。)