#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines W = int(readline()) m = map(int, read().split()) ABC = tuple(zip(m, m, m)) def gen_all_patterns(L, R): """L 日目約束なしの状態から、R日目約束なしの状態へ""" n = R - L dp = [[] for _ in range(n + 1)] dp[0] = [(0, 0)] for i, (a, b, c) in enumerate(ABC[L:R]): dp[i + 1] += [(x + a, y) for x, y in dp[i]] if i: dp[i + 1] += [(x - c, y + b) for x, y in dp[i - 1]] P = dp[-1] P.sort() Q = [] for x, y in P: while Q and Q[-1][0] <= x and Q[-1][1] <= y: Q.pop() Q.append((x, y)) return Q def solve(n): """ n日目約束なしを経由するパターンを解く """ P = gen_all_patterns(0, n)[::-1] Q = gen_all_patterns(n, W)[::-1] for qx, qy in Q: while P and P[-1][0] + qx < 0: P.pop() if not P: return yield P[-1][1] + qy answer = 0 for n in range(W // 2, W // 2 + 2): x = max(solve(n)) if answer < x: answer = x print(answer)