#!/usr/bin/python3 from collections import defaultdict params = input().split() item_count, recipe_count = int(params[0]), int(params[1]) costs = [] for cost in input().split(): costs.append(int(cost)) # defaultdic se chová jako slovník, ale pokud tázaný prvek neexistuje, # potají napřed do slovníku vloží výsledek volání funkce podané konstruktoru # (v našem případě funkce list). Nemusíme tedy později v kódu rozlišovat # případ, kdy tázaný předmět nejde vyrobit, neboť automaticky dostaneme # prázdný seznam receptů. recipes = defaultdict(list) for _ in range(recipe_count): params = input().split() product, input_count = int(params[0]), int(params[1]) ingredients = [] for ingredient in input().split(): ingredients.append(int(ingredient)) recipes[product].append(ingredients) cache = [] for _ in range(item_count): cache.append(None) # fukce f počítá nejlevnější způsob získání předmětu s daným id, # algoritmus je přesněji vysvětlen ve slovním popisu řešení def f(item_id: int) -> int: if cache[item_id] is not None: return cache[item_id] possible_costs = [costs[item_id]] for recipe in recipes[item_id]: recipe_cost = 0 for ingredient in recipe: recipe_cost += f(ingredient) possible_costs.append(recipe_cost) cost = min(possible_costs) cache[item_id] = cost return cost print(f(0))