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:
def solve():  
    ans = 0   
    N = int(input())
    KLR = []  
    for _ in range(N):
        KLR.append(list(map(int, input().split())))
    KLR.sort(key=lambda klr: -abs(klr[1] - klr[2]))
    train = [None] * N
    for klr in KLR:
        if klr[1] > klr[2]:
            pos = klr[0] - 1
            dir = -1
        elif klr[1] < klr[2]:
            pos = klr[0]
            dir = 1
        else: 
            pos = 0
            dir = 1
        if pos < 0 or pos >= N:
            ans += min(klr[1], klr[2])
            continue
        ok = False
        if train[pos] == None:
            ok = True
        else: 
            dir_ = train[pos]
            pos_ = pos
            while pos_ >= 0 and pos_ < N:
                if train[pos_] == None:
                    train[pos_] = dir_
                    train[pos] = None
                    ok = True
                    break
                pos_ += dir_
        if ok:
            train[pos] = dir
            ans += max(klr[1], klr[2])
        else: 
            ans += min(klr[1], klr[2])
    print(ans)
              
T = int(input())
              
for p in range(T):
    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:
        #    R[i] = float('inf')
        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:
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)
            r *= (-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)
            r *= (-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
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)
            if cnt == index + 1:
                l_filled = index
                continue
            left.add(index, 1)
            base += val
        else:
            if index <= r_filled:
                continue
            cnt = right.sum(index)
            if cnt == index + 1:
                r_filled = index
                continue
            right.add(index, 1)
            base += val
    print(base)

Submission status: Wrong Answer

Solution code:
INF = 10 ** 18
t = int(input())
for _ in range(t):
    n = int(input())
    li = [list(map(int, input().split())) for _ in range(n)]
    li.sort()
    ans = 0
    k, a = [0] * n, [0] * n
    for i in range(n):
        k[i], l, r = li[i]
        ans += r
        a[i] = l - r
    dp = [[-INF] * (n + 1) for _ in range(n + 1)]
    dp[0][0] = 0
    for i in range(n):
        for j in range(n):
            if k[i] > j:
                dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + a[i])
            if k[i] != n:
                dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
    print(max(dp[n]) + ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
#pyrival orz
import os
import sys
from io import BytesIO, IOBase

"""
    for _ in range(int(input())):
    n,m=map(int,input().split())
    n=int(input())
    a = [int(x) for x in input().split()]
"""

class SegmentTree:
    def __init__(self, data, default=0, func=max):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        """func of data[start, stop)"""
        start += self._size
        stop += self._size

        res_left = res_right = self._default
        while start < stop:
            if start & 1:
                res_left = self._func(res_left, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res_right = self._func(self.data[stop], res_right)
            start >>= 1
            stop >>= 1

        return self._func(res_left, res_right)

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)


def main():

    N,K=2000000,2000000
    for _ in range(int(input())):
        n=int(input())
        ans=0
        pv,nv=[],[]
        for _ in range(n):
            k,l,r=map(int,input().split())
            ans+=r
            l-=r
            if l>=0:
                pv.append((k,l))
            else:
                nv.append(l*N*K+k*K)
                # print(k,l)

        gt=[i for i in range(len(pv))]
        gt.sort(key=lambda v:pv[v][1])

        aa=SegmentTree([i for i in range(n)])

        for i in gt:
            k,l=pv[i]
            mx=aa.query(0,k)
            if mx<0:
                continue
            ans+=l
            aa[mx]=-1

        nv.sort()
        for i in range(len(nv)):
            nv[i]+=i
        gt=[i for i in range(len(nv))]
        gt.sort(key=lambda v:(nv[v]//K)%N)
        cnt=len(pv)
        vis=[True]*len(nv)
        aa=SegmentTree(nv,default=-1<<100)
        for i in gt:
            k=(nv[i]//K)%N
            # print("k",k,cnt)
            while cnt<k and vis[i]:
                mn=aa.query(0,len(nv))%K
                ans+=nv[mn]//N//K
                # print("mn",mn,i,k,cnt,nv[mn]//N//K)
                vis[mn]=False
                aa[mn]=(-1<<100)
                cnt+=1

            if vis[i]:
                cnt+=1
            vis[i]=False
            aa[i]=(-1<<100)
            # print(nv)
            # print(" ".join( str(aa.query(iii,iii+1)) for iii in range(len(nv))))
        print(ans)

# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:

class BinaryIndexedTree:
    def __init__(self, size):
        self.data = [0] * (size+1)
        self.msb = 1 << (size.bit_length()-1)
    
    def _add(self, i, w):
        i += 1
        while i < len(self.data):
            self.data[i] += w
            i += i & -i
    
    def _get_sum(self, i):
        res = 0
        while i > 0:
            res += self.data[i]
            i -= i & -i
        return res

    def __getitem__(self, i):
        """
        [0,i)
        """
        if isinstance(i, slice):
            if i.start is None:
                return self._get_sum(i.stop)
            else:
                return self._get_sum(i.stop) - self._get_sum(i.start)
        else:
            return 0 # fake value
    
    __setitem__ = _add
    
    def bisect_left(self, v):
        """
        return smallest i s.t v <= sum[:i]
        """
        i = 0
        k = self.msb
        while k > 0:
            i += k
            if i < len(self.data) and self.data[i] < v:
                v -= self.data[i]
            else:
                i -= k
            k >>= 1
        return i
    
    def bisect_right(self, v):
        """
        return smallest i s.t v < sum[:i]
        """
        i = 0
        k = self.msb
        while k > 0:
            i += k
            if i < len(self.data) and self.data[i] <= v:
                v -= self.data[i]
            else:
                i -= k
            k >>= 1
        return i
    
    bisect = bisect_right

def solve(KLR):
    min2 = lambda x,y: x if x < y else y

    N = len(KLR)
    offset = sum(min2(l,r) for k,l,r in KLR)
    KLR.sort()
    p = sorted((l-r,k,i,True) if l > r else (r-l,k,i,False) for i,(k,l,r) in enumerate(KLR))

    lbit = BinaryIndexedTree(N)
    rbit = BinaryIndexedTree(N)
    res = 0
    for v,k,i,is_l in p:
        if is_l:
            if lbit[:i]+1 <= k:
                lbit[i] += 1
                res += v
            else:
                rbit[i] += 1
        else:
            if rbit[i+1:N]+1 <= N-k:
                rbit[i] += 1
                res += v
            else:
                lbit[i] += 1
    return res+offset

if __name__ == '__main__':
    T = int(input())
    for t in range(T):
        N = int(input())
        KLR = [tuple(map(int,input().split())) for _ in range(N)]
        print(solve(KLR))

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    K = [0]*N
    R = [0]*N
    L = [0]*N
    arr_back = []
    arr_front = []
    ans = 0
    for i in range(N):
        K[i], L[i], R[i] = map(int,input().split(" "))
        if L[i] > R[i] :
            arr_front.append( ( K[i], R[i]-L[i], i) )
        elif L[i] < R[i] :
            arr_back.append( ( N-K[i], L[i]-R[i], i) )
        else :
            ans += L[i]
            
    arr_front.sort()
    arr_back.sort()

    front = back = 0

    for k, _, j in arr_front:
        if front < k :
            ans += L[j]
            front += 1
        else :
            ans += R[j]
        # print(ans)

    for k, _, j in arr_back:
        if back < k :
            ans += R[j]
            back += 1
        else :
            ans += L[j]
        # print(ans)

    return ans 

T = int(input())
for _ in range(T) :
    print(solve())

Submission status: Wrong Answer

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

t = int(input())
for x in range(t):
  n = int(input())
  plus = []
  minus = []
  res = 0
  for _ in range(n):
    k, l, r = map(int, input().split())
    if l > r:
      res += l
      plus.append((k, r-l))
    elif l < r:
      res += r
      minus.append((-k, l-r))
    else:
      res += l
  plus.sort()
  minus.sort()
  temp = 1
  for k, q in plus:
    if temp <= k:
      temp += 1
    else:
      res += q
  temp = n
  for k, q in minus:
    k = -k
    if temp > k:
      temp -= 1
    else:
      res += q
  print(res)

Submission status: Wrong Answer

Solution code:
def solve():
    ans = 0
    N = int(input())
    KLR = []
    for _ in range(N):
        KLR.append(list(map(int, input().split())))
    KLR.sort(key=lambda klr: -abs(klr[1] - klr[2]))
    print(KLR)
    train = [None] * N
    for klr in KLR:
        if klr[1] > klr[2]:
            pos = klr[0] - 1
            dir = -1
        elif klr[1] < klr[2]:
            pos = klr[0]
            dir = 1
        else:
            pos = 0
            dir = 1
        if pos >= N:
            ans += min(klr[1], klr[2])
            continue
        ok = False
        if train[pos] == None:
            ok = True
        else:
            dir_ = train[pos]
            pos_ = pos
            while pos_ >= 0 and pos_ < N:
                if train[pos_] == None:
                    train[pos_] = dir_
                    train[pos] = None
                    ok = True
                    break
                pos_ += dir_
        if ok:
            train[pos] = dir
            ans += max(klr[1], klr[2])
        else:
            ans += min(klr[1], klr[2])
    print(ans)

T = int(input())

for p in range(T):
    solve()

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappushpop

t = int(sys.stdin.buffer.readline())
buf = []
for _ in range(t):
    n = int(sys.stdin.buffer.readline())
    lll = []
    rrr = []
    ans = 0
    for i in range(n):
        k, l, r = map(int, sys.stdin.buffer.readline().split())
        if l >= r:
            lll.append((k, r - l))
            ans += l
        else:
            rrr.append((n - k, l - r))
            ans += r
    lll.sort()
    rrr.sort()
    q = []
    for k, rl in lll:
        if len(q) < k:
            heappush(q, rl)
        else:
            nrl = heappushpop(q, rl)
            ans += nrl
    q = []
    for k, lr in rrr:
        if len(q) < k:
            heappush(q, lr)
        else:
            nlr = heappushpop(q, lr)
            ans += nlr
           
    buf.append(ans)

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

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)
                if(len(cam)==0):
                    break
            if(hq):
                res += heappop(hq)

    ans[cyc] = res

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

Submission status: Wrong Answer

Solution code:
from heapq import *
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

class BitSum:
    def __init__(self, n):
        self.n = n + 1
        self.table = [0] * self.n

    def add(self, i, x):
        i += 1
        while i < self.n:
            self.table[i] += x
            i += i & -i

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

for _ in range(II()):
    n=II()
    hp=[]
    hpr=[]
    ans=0
    for _ in range(n):
        k,l,r=MI()
        d=r-l
        if d<0:heappush(hp,(r-l,l,r,k))
        elif d>0:heappush(hpr,(-r+l,l,r,k))
        else:ans+=r

    bit=BitSum(n+3)
    while hp:
        d,l,r,k=heappop(hp)
        if bit.sum(k)<k:
            ans+=l
            bit.add(k,1)
        else:
            ans+=r

    bit=BitSum(n+3)
    while hpr:
        d,l,r,k=heappop(hpr)
        k=n-k
        if bit.sum(k)<k:
            ans+=r
            bit.add(k,1)
        else:
            ans+=l

    print(ans)

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    K = [0]*N
    R = [0]*N
    L = [0]*N
    arr_back = []
    arr_front = []
    for i in range(N):
        K[i], L[i], R[i] = map(int,input().split(" "))
        if L[i] >= R[i] :
            arr_front.append( ( K[i], R[i]-L[i], i) )
        else :
            arr_back.append( ( N-K[i], L[i]-R[i], i) )
    
    arr_front.sort()
    arr_back.sort()

    ans = 0
    front = back = 0

    for k, _, j in arr_front:
        if front < k :
            ans += L[j]
            front += 1
        else :
            ans += R[j]
        # print(ans)

    for k, _, j in arr_back:
        if back < k :
            ans += R[j]
            back += 1
        else :
            ans += L[j]
        # print(ans)

    return ans 

T = int(input())
for _ in range(T) :
    print(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):
    diffs = [0] * N
    tmps = []
    bit_l = BinaryIndexedTree(N + 1)
    bit_r = BinaryIndexedTree(N + 1)
    for i in range(N):
        #if K[i] >= N:
        #    R[i] = float('inf')
        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:
class camel():
    def __init__(self, K, L, R):
        self.K = K
        self.R = R
        self.L = L
        self.diff = abs(L - R)


t = int(input())
for i in range(t):
    n = int(input())
    line = []
    for j in range(n):
        k, l, r = map(int, input().split())
        temp = camel(k, l, r)
        line.append(temp)
    line.sort(key=lambda x: x.diff, reverse=True)
    taken = set()
    small = 0
    ans = 0
    large = n-1
    for c in line:
        if c.R > c.L:
            if c.K <= large:
                temp = c.K
                temp1 = temp
                while taken.__contains__(temp):
                    temp += 1
                taken.add(temp)
                if temp == large:
                    while taken.__contains__(temp1):
                        temp1 -= 1
                    large = temp1
                ans += c.R
            else:
                ans += c.L
        elif c.L > c.R:
            if c.K > small:
                temp = c.K
                temp1 = temp
                while taken.__contains__(temp):
                    temp -= 1
                taken.add(temp)
                if temp == small:
                    while taken.__contains__(temp1):
                        temp1 += 1
                    small = temp1
                ans += c.L
            else:
                ans += c.R
        else:
            ans += c.L
    print(ans)

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]
            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]
            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:
import sys
input = sys.stdin.readline

t = int(input()[:-1])

for loop in range(t):
    n = int(input()[:-1])
    lg = []
    rg = []
    for i in range(n):
        k,l,r = map(int,input()[:-1].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:
#!/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):
    diffs = [0] * N
    tmps = []
    bit_l = BinaryIndexedTree(N + 1)
    bit_r = BinaryIndexedTree(N + 1)
    for i in range(N):
        if K[i] >= N:
            R[i] = float('inf')
        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:
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]
            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]
            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:
T=int(input())
for t in range(T):
    N=int(input())
    KLR=sorted([list(map(int,input().split())) for i in range(N)],key=lambda x:x[1]-x[2])
    a=0
    L,R=list(range(-1,N+1)),list(range(1,N+3))
    f=0
    x=0
    for k,l,r in KLR:
        if l==r or k==N:
            a+=l
        elif l>r:
            if L[R[k]]>0:
                a+=l
                L[R[k]],R[L[k]]=L[k],R[k]
                x+=1
            else:
                a+=r
        else:
            if f==0:
                f=1
                L,R=[0]*(x+2)+list(range(x+1,N+1)),[x+1]*(x+1)+list(range(x+2,N+3))
            if R[L[k+1]]<=N:
                a+=r
                L[R[k+1]],R[L[k+1]]=L[k+1],R[k+1]
            else:
                a+=l
    print(a)