Problem:


Score : 500 points

Problem Statement

We have N camels numbered 1,2,\ldots,N.
Snuke has decided to make them line up in a row.

The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise.

Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel.

Solve this problem for each of the T test cases given.

Constraints

All values in input are integers.

1 \leq T \leq 10^5

1 \leq N \leq 2 \times 10^{5}

1 \leq K_i \leq N

1 \leq L_i, R_i \leq 10^9

The sum of values of N in each input file is at most 2 \times 10^5.

Input

Input is given from Standard Input in the following format:

T
\mathrm{case}_1
\vdots
\mathrm{case}_T

Each case is given in the following format:

N
K_1 L_1 R_1
\vdots
K_N L_N R_N

Output

Print T lines. The i-th line should contain the answer to the i-th test case.

Sample Input 1

3
2
1 5 10
2 15 5
3
2 93 78
1 71 59
3 57 96
19
19 23 16
5 90 13
12 85 70
19 67 78
12 16 60
18 48 28
5 4 24
12 97 97
4 57 87
19 91 74
18 100 76
7 86 46
9 100 57
3 76 73
6 84 93
1 6 84
11 75 94
19 15 3
12 11 34

Sample Output 1

25
221
1354

In the first test case, it is optimal to line up the camels in the order 2, 1.

Camel 1 is not the frontmost camel, so its happiness will be 10.

Camel 2 is among the two frontmost camels, so its happiness will be 15.

In the second test case, it is optimal to line up the camels in the order 2, 1, 3.

Camel 1 is among the two frontmost camels, so its happiness will be 93.

Camel 2 is the frontmost camel, so its happiness will be 71.

Camel 3 is among the three frontmost camels, so its happiness will be 57.



Sample input:
3
2
1 5 10
2 15 5
3
2 93 78
1 71 59
3 57 96
19
19 23 16
5 90 13
12 85 70
19 67 78
12 16 60
18 48 28
5 4 24
12 97 97
4 57 87
19 91 74
18 100 76
7 86 46
9 100 57
3 76 73
6 84 93
1 6 84
11 75 94
19 15 3
12 11 34


Sample output:
25
221
1354

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint
from copy import deepcopy


sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 998244353

class BIT:
    def __init__(self, size):
        self.bit = [0] * size
        self.size = size
        self.total = 0

    def add(self, i, w):
        x = i + 1
        self.total += w
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        res = 0
        x = i + 1
        while x:
            res += self.bit[x - 1]
            x -= x & -x
        return res

    def get(self, i):
        if i == 0:
            return self.sum(0)
        return self.sum(i) - self.sum(i - 1)

    def interval_sum(self, i, j): # i <= x < j の区間
        return self.sum(j - 1) - self.sum(i - 1) if i else self.sum(j - 1)

    def search_r(self, l, r):
        #右側にだんだん伸ばしていく
        # l <= x < r
        ng = l - 1
        ok = r - 1
        while ng + 1 < ok:
            mid = (ng + ok) // 2
            if self.interval_sum(l, mid + 1):
                ok = mid
            else:
                ng = mid
        return ok

    def search_l(self, l, r):
        #左側にだんだん伸ばしていく
        # l <= x < r
        ng = r
        ok = l
        while ok + 1 < ng:
            mid = (ok + ng) // 2
            if self.interval_sum(mid, ng):
                ok = mid
            else:
                ng = mid
        return ok

t = I()
for _ in range(t):
    n = I()
    ans = 0
    L = []
    K = []
    for _ in range(n):
        k, l, r = LI()
        diff = l - r
        if diff > 0:
            L += [(diff, k, 1)]
        elif diff < 0:
            L += [(-diff, k, 0)]
        ans += min(l, r)

    L.sort(reverse=True)
    bit2 = BIT(n)
    bit3 = BIT(n)
    for j in range(n):
        bit2.add(j, 1)
        bit3.add(j, 1)
    for d, ki, flg in L:
        if flg:
            if bit2.sum(ki - 1) == 0:
                continue
            else:
                idx = bit2.search_l(0, ki)
                if bit3.get(idx) and bit3.search_r(idx, n):
                    bit3.add(idx, -1)
                    nxt_idx = bit3.search_r(idx, n)
                    bit3.add(nxt_idx, -1)
                bit2.add(idx, -1)
                ans += d
        else:
            if bit3.interval_sum(ki, n) == 0:
                continue
            else:
                idx2 = bit3.search_r(ki, n)
                if bit2.get(idx2) and bit2.search_l(0, idx2):
                    bit2.add(idx2, -1)
                    nxt_idx2 = bit2.search_l(0, idx2)
                    bit2.add(nxt_idx2, -1)
                bit3.add(idx2, -1)
                ans += d
    print(ans)

Submission status: Wrong Answer

Solution code:
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file=0




def possible(f,x):
    for i in range(x,0,-1):
        if f[i]==0:
            f[i]=1
            return x
    return 0

    
def solve():


    for _ in range(ii()):
    
        n=ii()
        a=[]
        b=[]
        for i in range(n):
            x,y,z=mi()
            a.append([z-y,x,y,z])
        f=[0]*(n+1)
        ans=0
        c=1
        a.sort()
        x=[]
        y=[]
        for i in a:
            if i[0]<0:
                x.append([i[1],i[2],i[3]])
            else:
                y.append([i[1],i[2],i[3]])
        x.sort()
        y.sort(reverse=True)
        c=1
        for i in x:
            c+=1
            if(possible(f,i[0])):
                x1=i[1]
            else:
                x1=i[2]
            ans+=x1
            # print(i,x1)
        for i in y:
            if i[0]<c:
                ans+=i[2]
            else:
                ans+=i[1]
            c+=1
        print(ans)




        
if __name__ =="__main__":

    if(file):

        if path.exists('input1.txt'):
            sys.stdin=open('input1.txt', 'r')
            sys.stdout=open('output1.txt','w')
        else:
            input=sys.stdin.readline
    solve()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)


class BinaryIndexedTree(object):

    def __init__(self, n):
        # index is 1-based so vals[0] never be used
        self.n = n
        self.vals = [0] * (n + 1)

    def add(self, i, v):
        while i <= self.n:
            self.vals[i] += v
            i += i & -i

    def sum(self, i):
        ret = 0
        while i > 0:
            ret += self.vals[i]
            i -= i & -i
        return ret

    def sum_range(self, l, r):
        # l and r are 1-based index and inclusive
        return self.sum(r) - self.sum(l - 1)


def solve(N, K, L, R):
    tmps = []
    bit_l = BinaryIndexedTree(N)
    bit_r = BinaryIndexedTree(N)
    for i in range(N):
        if K[i] >= N:
            tmps.append((-float('inf'), K[i], L[i], R[i]))
        else:
            tmps.append((abs(L[i] - R[i]), K[i], L[i], R[i]))
    tmps.sort(reverse=True)
    ret = 0
    for diff, k, l, r in tmps:
        if l > r:
            s = bit_l.sum_range(1, k)
            if s >= k:
                ret += r
            else:
                ret += l
                bit_l.add(k, 1)
        else:
            #s = bit_r.sum(N - k)
            s = bit_r.sum_range(1, N - k)
            if s >= N - k:
                ret += l
            else:
                ret += r
                bit_r.add(N - k, 1)
    print(ret)
    return

def main():
    T = int(input())
    for _ in range(T):
        N = int(input())
        K, L, R = [], [], []
        for i in range(N):
            k, l, r = map(int, input().split())
            K.append(k)
            L.append(l)
            R.append(r)
        solve(N, K, L, R)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
from heapq import heappop,heappush
t=int(input())
for _ in range(t):
	happy=0
	n=int(input())
	camel=[]
	for i in range(n):
		k,l,r=map(int,input().split())
		happy+=r
		if l-r>0:
			plus=1
		else:
			plus=0
		camel.append((l-r,k,plus))
	camel.sort(key=lambda x:(-x[2],x[1]))
	# print(camel)#前のものほど早く使うべき
	for i in range(n):
		if (i+1)<=camel[i][1]:
			happy+=camel[i][0]
	print(happy)

Submission status: Wrong Answer

Solution code:
import sys
from operator import itemgetter
input = sys.stdin.readline


class BIT1():
    """
    Binary Indexed Tree (1-indexed)
    """
    def __init__(self, n):
        self.n = n
        self.bit = [0] * (self.n + 1)
        self.data = [0] * (self.n + 1)

    def add(self, idx, x):
        # add x to idx-th element
        # idx: 1-indexed
        self.data[idx] += x
        while idx <= self.n:
            self.bit[idx] += x
            idx += (idx & (-idx))

    def sum(self, idx):
        # get sum of [1, idx]
        # idx: 1-indexed
        s = 0
        while idx:
            s += self.bit[idx]
            idx -= (idx & (-idx))
        return s

    def bisect_left(self, w):
        # condition : always all element is not minus
        # return minimum idx where bit.sum(idx) >= w
        if w <= 0:
            return 0
        idx = 0  # self.bit[idx] < w
        k = 1 << ((self.n).bit_length() - 1)
        while k > 0:
            if idx + k <= self.n and self.bit[idx + k] < w:
                w -= self.bit[idx + k]
                idx += k
            k = k >> 1
        return idx + 1


t = int(input())
for _ in range(t):
    n = int(input())
    camels = [tuple(map(int, input().split())) for _ in range(n)]
    camels.sort(key=lambda x: abs(x[1] - x[2]) if x[0] < n else 0,
                reverse=True)

    # print()
    # print('-' * 10)
    # print(*camels, sep='\n')

    bit = BIT1(n)
    ans = 0
    for i in range(1, n + 1):
        bit.add(i, 1)

    # print(bit.data)
    for k, l, r in camels:
        if k == n or l == r:
            ans += l
        else:
            s = bit.sum(k)
            if l > r:
                if s == 0:
                    # lを使えない
                    idx = bit.bisect_left(s + 1)
                    bit.add(idx, -1)
                    ans += r
                else:
                    idx = bit.bisect_left(s)
                    bit.add(idx, -1)
                    ans += l
            elif r > l:
                s2 = bit.sum(n)
                if s2 - s == 0:
                    # rを使えない
                    idx = bit.bisect_left(s)
                    bit.add(idx, -1)
                    ans += l
                else:
                    idx = bit.bisect_left(s + 1)
                    bit.add(idx, -1)
                    ans += r
            # print(f'{k}\t {idx}\t {abs(l - r) if k < n else 0}\t {l}\t {r}',
            #       bit.data)

    print(ans)

Submission status: Wrong Answer

Solution code:
for _ in range(int(input())):
  count = 0
  for i in range(1,int(input())+1):
    k,l,r = map(int,input().split())
    if i in list(range(1,k+1)): count += l
    else: count += r
  print(count)

Submission status: Wrong Answer

Solution code:
t=int(input())
for _ in range(t):
  n=int(input())
  s=0
  list1=[]
  list2=[]
  for i in range(n):
    k,l,r=map(int,input().split())
    s+=min(l,r)
    if l-r>0: list1.append((l-r,k))
    elif k!=n: list2.append((r-l,n-k))

  list1=sorted(list1, reverse=True, key=lambda x: x[0])
  list2=sorted(list2, reverse=True, key=lambda x: x[0])

  dic={p:0 for p in range(1,n+1)}
  for x in list1:
    w=x[1]
    dic[w]+=1
    if dic[w]<=w: s+=x[0]

  dic={p:0 for p in range(1,n+1)}
  for x in list2:
    w=x[1]
    dic[w]+=1
    if dic[w]<=w: s+=x[0]
  print(s)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)


class BinaryIndexedTree(object):

    def __init__(self, n):
        # index is 1-based so vals[0] never be used
        self.n = n
        self.vals = [0] * (n + 1)

    def add(self, i, v):
        while i <= self.n:
            self.vals[i] += v
            i += i & -i

    def sum(self, i):
        ret = 0
        while i > 0:
            ret += self.vals[i]
            i -= i & -i
        return ret

    def sum_range(self, l, r):
        # l and r are 1-based index and inclusive
        return self.sum(r) - self.sum(l - 1)


def solve(N, K, L, R):
    tmps = []
    bit_l = BinaryIndexedTree(N)
    bit_r = BinaryIndexedTree(N)
    for i in range(N):
        if K[i] >= N:
            tmps.append((-float('inf'), K[i], L[i], R[i]))
        else:
            tmps.append((abs(L[i] - R[i]), K[i], L[i], R[i]))
    tmps.sort(reverse=True)
    ret = 0
    for diff, k, l, r in tmps:
        if l > r:
            s = bit_l.sum(k)
            if s >= k:
                ret += r
            else:
                ret += l
                bit_l.add(k, 1)
        else:
            s = bit_r.sum(N - k)
            if s >= N - k:
                ret += l
            else:
                ret += r
                bit_r.add(N - k, 1)
    print(ret)
    return

def main():
    T = int(input())
    for _ in range(T):
        N = int(input())
        K, L, R = [], [], []
        for i in range(N):
            k, l, r = map(int, input().split())
            K.append(k)
            L.append(l)
            R.append(r)
        solve(N, K, L, R)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# import sys
# input = sys.stdin.readline

t = int(input())

for loop in range(t):
    n = int(input())
    lg = []
    rg = []
    for i in range(n):
        k,l,r = map(int,input().split())
        if l > r:
            lg.append([k,l,r])
        else:
            rg.append([n-k,l,r])
    lg.sort(key=lambda x:(x[0],-x[1]))
    rg.sort(key=lambda x:(x[0],-x[2]))
    fill = 0
    ans = 0
    for l in lg:
        if l[0] > fill:
            fill += 1
            ans += l[1]
        else:
            ans += l[2]
    fill = 0
    for r in rg:
        if r[0] > fill:
            fill += 1
            ans += r[2]
        else:
            ans += r[1]
    # print(lg)
    # print(rg)
    print(ans)

Submission status: Wrong Answer

Solution code:
for _ in range(int(input())):
  count = 0
  for i in range(int(input())):
    k,l,r = map(int,input().split())
    if i+1 in range(1,k+1): count += l
    else: count += r
  print(count)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 8)

def input(): return sys.stdin.readline().strip()
def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    T = Z()
    ans = []
    for _ in range(T):
        N = Z()
        camel = []
        for _ in range(N):
            k, l, r = ZZ()
            camel.append([k, -l, r])
        camel.sort()
        isseen = [False] * N
        order = 1
        cc = 0
        for i in range(N):
            k, l, r = camel[i]
            l *= (-1)
            if l > r:
                isseen[i] = True
                if order <= k: cc += l
                else: cc += r
                order += 1
            else: continue
        for i in range(N):
            if isseen[i]: continue
            k, l, r = camel[i]
            l *= (-1)
            isseen[i] = True
            if order <= k: cc += l
            else: cc += r
            order += 1
        ans.append(cc)

    for a in ans:
        print(a)

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)


class BinaryIndexedTree(object):

    def __init__(self, n):
        # index is 1-based so vals[0] never be used
        self.n = n
        self.vals = [0] * (n + 1)

    def add(self, i, v):
        while i <= self.n:
            self.vals[i] += v
            i += i & -i

    def sum(self, i):
        ret = 0
        while i > 0:
            ret += self.vals[i]
            i -= i & -i
        return ret

    def sum_range(self, l, r):
        # l and r are 1-based index and inclusive
        return self.sum(r) - self.sum(l - 1)


def solve(N, K, L, R):
    tmps = []
    bit_l = BinaryIndexedTree(N)
    bit_r = BinaryIndexedTree(N)
    for i in range(N):
        if K[i] >= N:
            tmps.append((-float('inf'), K[i], L[i], R[i]))
        else:
            tmps.append((abs(L[i] - R[i]), K[i], L[i], R[i]))
    tmps.sort(reverse=True)
    ret = 0
    for diff, k, l, r in tmps:
        if l > r:
            s = bit_l.sum(k)
            if s >= k:
                ret += r
            else:
                ret += l
                bit_r.add(k, 1)
        else:
            bit = bit_r
            s = bit_r.sum(N - k)
            if s >= N - k:
                ret += l
            else:
                ret += r
                bit_r.add(N - k, 1)
    print(ret)
    return

def main():
    T = int(input())
    for _ in range(T):
        N = int(input())
        K, L, R = [], [], []
        for i in range(N):
            k, l, r = map(int, input().split())
            K.append(k)
            L.append(l)
            R.append(r)
        solve(N, K, L, R)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
for _ in range(int(input())):
  count = 0
  for i in range(int(input())):
    k,l,r = map(int,input().split())
    if i+1 in range(1,k): count += l
    else: count += r
  print(count)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline

class BinaryIndexedTree:
    # Initialize BIT with non-zero value
    def __init__(self, array):
        self.len = len(array)
        self.data = [0] + array
        self.build()

    def build(self):
        for i in range(1, self.len):
            if i + (i & -i) > self.len:
                continue
            self.data[i + (i & -i)] += self.data[i]

    # Add w to a[x] (0-indexed)
    def add(self, x, w):
        x += 1
        while x <= self.len:
            self.data[x] += w
            x += x & -x

    # Get Sum of a[0 : x) (0-indexed)
    def sum(self, x):
        ret = 0
        while x > 0:
            ret += self.data[x]
            x -= x & -x
        return ret

    # Get first index s.t. sum a[0 : index) >= w
    def bisect_left(self, w):
        if w <= 0:
            return 0
        x = 0
        delta = pow(2, (self.len - 1).bit_length())
        while delta > 0:
            if x + delta <= self.len and self.data[x + delta] < w:
                w -= self.data[x + delta]
                x += delta
            delta >>= 1
        return x

t = int(input())
for _ in range(t):
    n = int(input())
    q = []
    base = 0
    left = BinaryIndexedTree([0] * n)
    right = BinaryIndexedTree([0] * n)
    for _ in range(n):
        k, l, r = map(int, input().split())
        if k == n:
            base += l
            continue
        if l >= r:
            q.append((l-r, 0, k-1))
            base += r
        else:
            q.append((r-l, 1, n-k-1))
            base += l
    q.sort(reverse=True)
    l_filled = -1 
    r_filled = -1
    for val, lr, index in q:
        if lr == 0:
            if index <= l_filled:
                continue
            cnt = left.sum(index + 1)
            if cnt == index + 1:
                l_filled = index
                continue
            left.add(index, 1)
            base += val
        else:
            if index <= r_filled:
                continue
            cnt = right.sum(index + 1)
            if cnt == index + 1:
                r_filled = index
                continue
            right.add(index, 1)
            base += val
    print(base)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))
import heapq


t = readint()
ans = []

for _ in range(t):
    n = readint()
    a = []
    b = []
    score = 0
    for i in range(n):
        k,l,r = readints()
        if k==n:
            score += l
        elif l>r:
            a.append([k,l,r])
            score += l
        elif l<r:
            b.append([n-k,l,r])
            score += r
        else:
            score += r
    a.sort()
    b.sort()
    left = []
    right = []
    heapq.heapify(left)
    heapq.heapify(right)
    lenl = 0
    lenr = 0
    for k,l,r in a:
        if k>lenl:
            heapq.heappush(left,[l,r])
            lenl += 1
        else:
            if l-r>left[0][0]-left[0][1]:
                y = heapq.heappop(left)
                heapq.heappush(left,[l,r])
                score -= y[0]
                score += y[1]
            else:
                score -= l
                score += r
    for k,l,r in b:
        if k>lenr:
            heapq.heappush(right,[l,r])
            lenr += 1
        else:
            if r-l>right[0][1]-right[0][0]:
                y = heapq.heappop(right)
                heapq.heappush(right,[l,r])
                score -= y[1]
                score += y[0]
            else:
                score -= r
                score += l
    ans.append(score)
printrows(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import *
sys.setrecursionlimit(2*10**5+100)

def dfs(i, l):
    if i==N:
        return 0
        
    K, L, R = KLR[i]
    res = 0
    if i+1<=K:
        res = max(res, dfs(i+1, l+1)+L)
    if i-l+1<=N-K:
        res = max(res, dfs(i+1, l)+R)
    return res

T = int(input())

for _ in range(T):
    N = int(input())
    KLR = [tuple(map(int, input().split())) for _ in range(N)]
    KLR.sort(key=lambda t: t[0])
    print(dfs(0, 0))

Submission status: Wrong Answer

Solution code:
import heapq
def solve():
    N = int(input())
    que = []
    heapq.heapify(que)
    useless = []
    ans = 0
    left = 0
    right = N-1
    Index = [-1 for i in range(N)]
    for i in range(N):
        K, L, R = map(int, input().split())
        if L > R:
            heapq.heappush(que, (-L+R, K, "left"))
        else:
            heapq.heappush(que, (-R+L, K, "right"))
    while que:
        value, index, which = heapq.heappop(que)
        value *= -1
        if which == "left":
            if left <= index-1:
                Index[left] = L
                left += 1
            elif left > index-1:
                # case umpossible
                useless.append(R)
        elif which == "right":
            if right > index-1:
                Index[right] = R
                right -= 1
            elif right <= index-1:
                useless.append(L)
    for i in range(N):
        if Index[i] > 0:
            ans += Index[i]
    ans += sum(useless)
    print(ans)


def main():
    T = int(input())
    for i in range(T):
        solve()


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from heapq import heappop,heappush

t = int(readline())
q = list(map(int,read().split()))

now = 0
ans = [0] * t
for cyc in range(t):
    n = q[now]
    klr = q[now+1: now+1+3*n]
    now = now+1+3*n

    it = iter(klr)
    lc = []
    rc = []
    min_p = 0
    for x,y,z in zip(it,it,it):
        if(y==z):
            min_p += y
        elif(y>z):
            min_p += z
            lc.append((x,y-z))
        else:
            min_p += y
            rc.append((n-x,z-y))

    res = min_p
    lc.sort()
    rc.sort()

    for cam in [lc,rc]:
        hq = []
        for i in range(n,0,-1):
            if(len(cam)==0):
                continue
            while(cam[-1][0] == i):
                x,p = cam.pop()
                heappush(hq,p*-1)
                if(len(cam)==0):
                    break
            if(hq):
                res += heappop(hq)*-1

    ans[cyc] = res

print('\n'.join(map(str,ans)))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
Q = I()


for _ in range(Q):
  N = I()
  data = ILL(N)
  data.sort(key=lambda x:-abs(x[1]-x[2]))
  ans = 0
  MAE = [i for i in range(N)]
  def CANSIT_MAE(x):
    if MAE[x] == -1:
      return -1
    elif MAE[x] == x:
      MAE[x] = x-1
      return x
    else:
      MAE[x] = CANSIT_MAE(MAE[x])
      return MAE[x]
  USHIRO = [i for i in range(N)]
  def CANSIT_USHIRO(x):
    if USHIRO[x] == -1:
      return -1
    elif USHIRO[x] == x:
      USHIRO[x] = x-1
      return x
    else:
      USHIRO[x] = CANSIT_USHIRO(USHIRO[x])
      return USHIRO[x]
  for K,L,R in data:
    if L==R or K==N:
      ans += L
    elif L>R:
      if CANSIT_MAE(K-1)!=-1:
        ans += L
      else:
        ans += R
    else:
      if CANSIT_USHIRO(N-K)!=-1:
        ans += R
      else:
        ans += L
  print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from heapq import heappop,heappush

t = int(readline())
q = list(map(int,read().split()))

now = 0
ans = [0] * t
for cyc in range(t):
    n = q[now]
    klr = q[now+1: now+1+3*n]
    now = now+1+3*n

    it = iter(klr)
    lc = []
    rc = []
    min_p = 0
    for x,y,z in zip(it,it,it):
        if(y==z):
            min_p += y
        elif(y>z):
            min_p += z
            lc.append((x,y-z))
        else:
            min_p += y
            rc.append((n-x,z-y))

    res = min_p
    lc.sort()
    rc.sort()
    print(lc)

    for cam in [lc,rc]:
        hq = []
        for i in range(n,0,-1):
            if(len(cam)==0):
                continue
            while(cam[-1][0] == i):
                x,p = cam.pop()
                heappush(hq,p*-1)
                if(len(cam)==0):
                    break
            if(hq):
                res += heappop(hq)*-1

    ans[cyc] = res

print('\n'.join(map(str,ans)))