""" Greedy submission. This should be judged as WA. When choosing the day to visit each of the "child farms", compute the cost to visit each child farm on each candidate day. Then find the best day to visit each child farm and the second best day. Whichever farm has the greatest difference between best day and second best day is the farm that should be visited on its best day. Remove that farm and day from consideration and repeat. """ from collections import defaultdict from sys import stdin class Node: def __init__(self, idd): self.id = idd self.parent = None self.coefficient = None self.target_day = None self.adj = [] def main(): n = int(stdin.readline()) nodes = [Node(i) for i in range(n + 1)] nodes[0].coefficient = 0 nodes[0].target_day = 0 for i in range(n): c, d, r = map(int, stdin.readline().split(" ")) nodes[r].adj.append(i+1) nodes[i+1].parent = r nodes[i+1].coefficient = c nodes[i+1].target_day = d dp = {} best = solve(0, 0, dp, nodes) print(best) def solve(farm, day, dp, nodes): if (farm, day) in dp: return dp[(farm, day)] self_day_delta = nodes[farm].target_day - day self_cost = nodes[farm].coefficient * self_day_delta * self_day_delta total_cost = self_cost for adj_farm_id in nodes[farm].adj: for adj_day in range(day+1, day+1+len(nodes[farm].adj)): solve(adj_farm_id, adj_day, dp, nodes) remaining_days = {visit_day for visit_day in range(day+1, day+1+len(nodes[farm].adj))} remaining_farms = {farm_id for farm_id in nodes[farm].adj} while remaining_farms: if len(remaining_farms) == 1: total_cost += dp[(remaining_farms.pop(), remaining_days.pop())] break farm_costs = defaultdict(list) cost_deltas = [] for next_farm in remaining_farms: for next_day in remaining_days: farm_costs[next_farm].append((dp[(next_farm, next_day)], next_day)) farm_costs[next_farm].sort() best_cost = farm_costs[next_farm][0][0] second_best_cost = farm_costs[next_farm][1][0] best_day = farm_costs[next_farm][0][1] cost_deltas.append((second_best_cost - best_cost, next_farm, best_day)) cost_deltas.sort(reverse=True) _, chosen_farm, chosen_day = cost_deltas[0] total_cost += dp[(chosen_farm, chosen_day)] remaining_farms.remove(chosen_farm) remaining_days.remove(chosen_day) dp[(farm, day)] = total_cost return dp[(farm, day)] if __name__ == "__main__": main()