module IntMap = Map.Make (struct
  type t = int
  let compare = compare
end)

let rec inchworm i j m (((k, d) :: klrs') as klrs) c =
  if i < k
  then c klrs j m
  else inchworm i (j + 1) (IntMap.update d (fun o -> Some (1 + Option.value ~default:0 o)) m) klrs' c

let rec sieve i k j m =
  if j <= i + 1
  then k j m
  else
    sieve i k (j - 1) @@
    match IntMap.min_binding m with
    | (d, 1) -> IntMap.remove d m
    | (d, n) -> IntMap.add d (n - 1) m

let rec solve n i klrs j m =
  if n <= i
  then IntMap.fold (fun d n -> ( + ) @@ d * n) m 0
  else
    inchworm i j m klrs @@ fun klrs ->
      sieve i @@ solve n (i + 1) klrs

let () = Scanf.scanf "%d\n" @@ fun t ->
  for i = 1 to t do
    Scanf.scanf "%d\n" @@ fun n ->
      let klrs = List.init n @@ fun _ ->
        Scanf.scanf "%d %d %d\n" @@ fun k l r -> (k - 1, l, r) in
      let left, right = List.partition (fun (_, l, r) -> r <= l) klrs in
      Printf.printf "%d\n" @@
      List.fold_left (fun sum (_, l, r) -> sum + min l r) 0 klrs
      + solve n 0
          (List.sort (fun (k, _) (k', _) -> compare k k')
            ((n, 0) :: List.map (fun (k, l, r) -> (k, l - r)) left)) 0 IntMap.empty
      + solve n 0
          (List.sort (fun (k, _) (k', _) -> compare k k')
            ((n, 0) :: List.filter_map (fun (k, l, r) -> if n - k - 2 < 0 then None else Some (n - k - 2, r - l)) right)) 0 IntMap.empty
  done