from itertools import combinations
class Solution:
def __init__(self, cost, types):
self.element_info = []
self.cost = cost
self.types = types
def getbool(self, cost, comb_list):
minrel = float('inf')
lens = self.types
cur_cost = 0
cur_type = -1
for i in range(lens):
cur_cost += comb_list[i][2]
next_type = comb_list[i][0]
if next_type != cur_type and (comb_list[0][0] != comb_list[lens - 1][0]):
if cur_cost <= cost:
cur_type = next_type
cur_rel = comb_list[i][1]
if cur_rel <= minrel:
minrel = cur_rel
else:
return 0
else:
return 0
return minrel
def getmaxreliabily(self):
maxreliabily = 0
for elem_comb in combinations(self.element_info, self.types):
reliabily = self.getbool(self.cost, elem_comb)
if reliabily >= maxreliabily:
maxreliabily = reliabily
if maxreliabily == 0:
return -1
else:
return maxreliabily
if __name__ == "__main__":
inpss = input().strip().split()
fee, kind = int(inpss[0]), int(inpss[1])
n = int(input().strip())
elem_list = []
while True:
line = list(map(int, input().strip().split()))
if len(line) == 0:
break
else:
elem_list.append(line)
solution = Solution(cost=fee, types=kind)
solution.element_info = elem_list
print(solution.getmaxreliabily())
