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():
  T = int(input())
  ans = [0]*T
  for t in range(T):
    N = int(input())
    left = []
    right = []
    for i in range(N):
      k,l,r = map(int, input().split())
      if k==N:
        ans[t] += l
      elif l>r:
        left.append([k,l-r])
        ans[t] += r
      elif l<r:
        right.append([k,r-l])
        ans[t] += l
      else:
        ans[t] += l
    left.sort(key = lambda x:(-x[0],-x[1]))
    right.sort(key = lambda x:(x[0],-x[1]))
    if len(left):
      now = left[0][1]
      ans[t] += left[0][1]
      for i in range(1,len(left)):
        while left[i][0]>=now:
          left[i][0] -= 1
        ans[t] += left[i][1]
        now -= 1
        if now==0:
          break
    if len(right):
      now = right[0][1]
      ans[t] += right[0][1]
      for i in range(1,len(right)):
        while right[i][0]<=now:
          right[i][0] += 1
        ans[t] += right[i][1]
        now -= 1
        if now==0:
          break
  return ans
print(*solve(),sep='\n')

Submission status: Wrong Answer

Solution code:
T = int(input())
ans = []
for t in range(T):
    tmpans =0
    N = int(input())
    KLR = [list(map(int,input().split())) for i in range(N)]
    goL =[]#Lに行きたい人
    goR =[]
    for i in range(N):
        if KLR[i][1] > KLR[i][2]:
            goL.append(KLR[i])
        else:
            goR.append(KLR[i])

    is_closed=[0]*(N+1)#i番目があいているか
    goL.sort(key=lambda x:x[1]-x[2])
    goR.sort(key=lambda x:x[2]-x[1])


    for i in goL:
        j = i[0]#以内にはいりたい
        while j > 0:
            if is_closed[j]==0:
                tmpans += i[1]
                is_closed[j]=1
                break
            j-=1
        if j==0:
            tmpans+=i[2]

    is_closed = [0]*(N+1)
    for i in goR:
        j = i[0]+1#以内にはいりたい
        while j < N+1:
            if is_closed[j]==0:
                tmpans += i[2]
                is_closed[j]=1
                break
            j+=1

        if j==N+1:
            tmpans+=i[1]
    ans.append(tmpans)

for i in range(len(ans)):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import heapq
import sys
input=sys.stdin.readline

t=int(input())
for _ in range(t):
    n=int(input())
    arr=[list(map(int,input().split())) for _ in range(n)]
    head=[]
    tail=[]
    for k,l,r in arr:
        if l>=r or k==n:
            head.append((k,l,r))
        else:
            tail.append((k,l,r))
    head=sorted(head,key=lambda x:x[0])
    q=[]
    cnt=0
    ans=[]
    for k,l,r in head:
        heapq.heappush(q,(l-r,l))
        cnt+=1
        while cnt>k:
            tmp,val=heapq.heappop(q)
            ans.append((tmp,val-tmp))
            cnt-=1
    ans+=list(q)
    cnt=len(ans)
    tail2=[]
    for k,l,r in tail:
        if k<=cnt:
            ans.append((l-r,r))
        else:
            tail2.append((k,l,r))
    tail2=sorted(tail2,reverse=True,key=lambda x:x[0])
    q2=[]
    cnt2=0
    for k,l,r in tail2:
        heapq.heappush(q2,(r-l,r))
        cnt2+=1
        while cnt2>(n-k+1):
            tmp,val=heapq.heappop(q2)
            ans.append((tmp,val-tmp))
            cnt2-=1
    ans+=list(q2)
    ret=0
    for _,val in ans:
        ret+=val
    print(ret)

Submission status: Wrong Answer

Solution code:
from heapq import heappop, heappush

t = int(input())
for _ in range(t):
    C = []
    n = int(input())
    for _ in range(n):
        k, l, r = map(int, input().split())
        C.append([k, l, r])
    ans = 0
    left = []
    right = []
    res = 0
    for i in range(n):
        k, l, r = C[i]
        if l > r:
            heappush(left, [C[i][0], i])
        elif r > l:
            heappush(right, [C[i][0], i])
        else:
            ans += r
            res += 1
    cnt = 1
    while left:
        v1, v2 = heappop(left)
        if cnt <= v1:
            ans += C[v2][1]
        else:
            ans += C[v2][2]
        cnt += 1
    while right:
        v1, v2 = heappop(right)
        if cnt <= v1:
            if cnt + res > v1:
                cnt += res
                res = 0
                ans += C[v2][2]
            else:
                ans += C[v2][1]
        else:
            ans += C[v2][2]
        cnt += 1
    print(ans)

Submission status: Wrong Answer

Solution code:
T = int(input())
ans = []
for t in range(T):
    tmpans =0
    N = int(input())
    KLR = [list(map(int,input().split())) for i in range(N)]
    goL =[]#Lに行きたい人
    goR =[]
    for i in range(N):
        if KLR[i][1] > KLR[i][2]:
            goL.append(KLR[i])
        else:
            goR.append(KLR[i])

    is_closed=[0]*(N+1)#i番目があいているか
    goL.sort(key=lambda x:x[1])
    goR.sort(key=lambda x:x[2])


    for i in goL:
        j = i[0]#以内にはいりたい
        while j > 0:
            if is_closed[j]==0:
                tmpans += i[1]
                is_closed[j]=1
                break
            j-=1
        if j==0:
            tmpans+=i[2]

    is_closed = [0]*(N+1)
    for i in goR:
        j = i[0]+1#以内にはいりたい
        while j < N+1:
            if is_closed[j]==0:
                tmpans += i[2]
                is_closed[j]=1
                break
            j+=1

        if j==N+1:
            tmpans+=i[1]
    ans.append(tmpans)

for i in range(len(ans)):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
T = int(input())
for _ in range(T):
  N = int(input())
  base = 0
  A = []
  B = [0 for _ in range(N)]
  C =[]
  for i in range(N):
    K, L, R = map(int,input().split()) 
    tmp = min(L,R)
    L -= tmp
    R -= tmp
    if L > R:
      A.append((L,K,0))
    if R >= L:
      A.append((R,K,1))
    base += tmp
  A.sort(reverse = True)
  
  l = 0
  r = N-1
  for a in A:
    if a[2] == 0:
      if l < a[1]:
        l += 1
        base += a[0] 
    else:
      if r >= a[1]:
        r -= 1
        base += a[0]
  print(base)
  
#print(A)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
class SegmentTree:
    def __init__(self, n, ele, segfun):
        self.ide_ele = ele
        self.segfun = segfun
        self.n = n
        self.N0 = 1 << n.bit_length()
        self.data = [self.ide_ele] * (self.N0 * 2)

    def update_add(self, l, r, val):
        l += self.N0
        r += self.N0
        while l < r:
            if l & 1:
                self.data[l] += val
                l += 1
            if r & 1:
                self.data[r - 1] += val
                r -= 1
            l //= 2
            r //= 2

    def query(self, i):
        i += len(self.data) // 2
        ret = self.data[i]
        while i > 0:
            i //= 2
            ret = self.segfun(ret, self.data[i])
        return ret

n = int(readline())
for _ in range(n):
  t = int(readline())
  chk = []
  for i in range(t):
    k,l,r = map(int,readline().split())
    chk.append((abs(l-r),l,r,k))
  chk.sort(reverse=True)
  S = SegmentTree(t,0,lambda a, b: a+b)
  E = SegmentTree(t,0,lambda a, b: a+b)
  ans = 0
  for c,l,r,k in chk:
    if k == t or l == r:
      ans += l
    elif l > r:
      if S.query(k-1) <= k:
        ans += l
        S.update_add(k-1,t,1)
      else:
        ans += r
    elif r > l:
      if E.query(k) <= t-k-1:
        ans += r
        E.update_add(0,k,1)
      else:
        ans += l
  print(ans)

Submission status: Wrong Answer

Solution code:
t = int(input())
while t:
    t-=1
    n = int(input())
    klr = [list(map(int, input().split())) for i in range(n)]
    klr.sort(key=lambda x:(x[0],-x[1]))
    ans = 0
    l = 0
    r = 0
    inc = 0
    for i in range(n):
        if(i>0):
            inc += klr[i][0]-klr[i-1][0]
        if (klr[i][1]>=klr[i][2] and l<klr[i][0]) or r>=n-klr[i][0]:
            if klr[i][1]<klr[i][2] and max(r-inc,0)<n-klr[i][0]:
                ans += klr[i][2]
                r += 1
                dec = r - (n-klr[i][0])
                inc -= dec
            else:
                ans += klr[i][1]
                l += 1
        else:
            ans += klr[i][2]
            r += 1
    print(ans)

Submission status: Wrong Answer

Solution code:
T = int(input())
for _ in range(T):
  N = int(input())
  base = 0
  A = []
  B = [0 for _ in range(N)]
  C =[]
  for i in range(N):
    K, L, R = map(int,input().split()) 
    tmp = min(L,R)
    L -= tmp
    R -= tmp
    if L > R:
      A.append((L,K,0))
    if R >= L:
      A.append((R,K,1))
    base += tmp
  A.sort(reverse = True)
  
  l = 0
  r = N-1
  for a in A:
    if a[2] == 0:
      if l < a[1]:
        l += 1
        base += a[0] 
    else:
      if r >= a[1]:
        r -= 1
        base += a[0]
  print(base)
  
print(A)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
T = int(input())

def process(arr):
    arr.sort()
    baseS = 0
    diffS = 0
    q = []
    length = 0
    for K, L, R in arr1:
        baseS += R
        diff = L - R
        heappush(q, diff)
        diffS += diff
        length += 1
        while length > K:
            d = heappop(q)
            diffS -= d
            length -= 1
    return baseS + diffS

for _ in range(T):
    N = int(input())
    arr1 = []
    arr2 = []
    for _ in range(N):
        K, L, R = list(map(int, input().split()))
        if L > R:
            arr1.append((K, L, R))
        else:
            arr2.append((N-K, R, L))
    print(process(arr1) + process(arr2))

Submission status: Wrong Answer

Solution code:
def solve():
  n = int(input())
  a = [-float("inf") for _ in range(n+1)]
  b = [0 for _ in range(n+1)]
  c = [0 for _ in range(n+1)]
  for _ in range(n):
    k,l,r = map(int,input().split())
    c[k] += 1
    if a[k] == -float("inf"):
      a[k] = l-r
    else:
      if l-r > a[k]:
        a[k] = l-r
    b[k] += r
  s = sum(b)
  e = 0
  f = 0
  m1 = -float("inf")
  m2 = float("inf")
  for i in range(1,n+1):
    if a[i] != -float("inf"):
      if a[i] < 0:
        e += c[i]
        f += 1
        if a[i] > m1:
          m1 = a[i]
      else:
        if m2 > a[i]:
          m2 = a[i] 
    else:
      f += 1
  if e >= f:
    for i in range(1,n+1):
       if a[i] >= 0:
          s += b[i]
    print(s)
    if m1+m2 <= 0:
      s -= m2
    else:
      s += m1
  else:
    for i in range(1,n+1):
      if a[i] >= 0:
        s += b[i]
    print(s)
t = int(input())
for _ in range(t):
  solve()

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.buffer.readline

t = int(input())


class SegmentTree:
    ele = 0

    # SEG木は1-index
    # Aに関しては0-index

    def __init__(self, n):  # Aは0-idx
        self.n = n
        self.num = 2 ** ((self.n - 1).bit_length())
        self.SEG = [self.ele] * (2 * self.num)

    def func(self, a, b):
        return a + b

    def search(self, idx):
        return self.SEG[idx + self.num]

    def initialize(self, A):
        for i in range(self.n):
            self.SEG[i + self.num] = A[i]
        for i in range(self.num - 1, 0, -1):
            self.SEG[i] = self.func(self.SEG[2 * i], self.SEG[2 * i + 1])

    def update(self, idx, val):
        idx += self.num
        self.SEG[idx] = val
        idx //= 2
        while idx:
            self.SEG[idx] = self.func(self.SEG[2 * idx], self.SEG[2 * idx + 1])
            idx //= 2

    def query(self, left, right):
        # maspy式。開区間のママ処理する
        # left, rightで値を分けているのは交換法則不成立のときのため
        # 開区間→Rが奇数→右端が偶数→1ずらしてから計算
        # 　下から上への遷移は2で割る
        # juppy氏は閉区間に直していた
        resleft = self.ele
        resright = self.ele
        left += self.num
        right += self.num
        while right - left > 0:
            if left % 2 == 1:
                resleft = self.func(resleft, self.SEG[left])
                left += 1
            if right % 2 == 1:
                right -= 1
                resright = self.func(resright, self.SEG[right])
            left //= 2
            right //= 2
        return self.func(resleft, resright)


def search_upper_smaller(a, SEG):
    ng = a
    ok = n - 1

    if SEG.query(a, n) == n - a:
        return False, 0
    while ok - ng > 1:
        mid = (ok + ng) // 2

        if SEG.query(a, mid) == (mid - a):
            ng = mid
        else:
            ok = mid
    return True, ok


def search_upper_bigger(a, SEG):
    ng = n
    ok = a + 1
    if a == n - 1:
        if SEG.search(n - 1) == 1:
            return False, 0
        else:
            return True, n - 1
    if SEG.query(a + 1, n) == n - a - 1:
        return False, 0
    while ng - ok > 1:
        mid = (ok + ng) // 2

        if SEG.query(mid, n) == (n - mid):
            ng = mid
        else:
            ok = mid
    return True, ok


def search_lower_bigger(a, SEG):
    ng = a + 1
    ok = 0
    if SEG.query(0, a) == a:
        return False, 0
    while ng - ok > 1:
        mid = (ok + ng) // 2
        if SEG.query(mid, a) == (a - mid):
            ng = mid
        else:
            ok = mid
    return True, ok


def search_lower_smaller(a, SEG):
    ng = -1
    ok = a
    if SEG.query(0, a) == a:
        return False, 0
    while ok - ng > 1:
        mid = (ok + ng) // 2
        if SEG.query(0, mid) == (mid - 0):
            ng = mid
        else:
            ok = mid
    return True, ok


for _ in range(t):
    n = int(input())
    kouho = []
    res = 0
    SEG = SegmentTree(n)
    for _ in range(n):
        k, l, r = map(int, input().split())
        if l - r > 0:
            kouho.append([l, r, 1, k - 1])
        elif r - l > 0:
            kouho.append([r, l, 0, k - 1])
        else:
            res += l
        kouho.sort(reverse=True)
    for bigger, smaller, hantei, basho in kouho:
        if hantei:  # 左にいたい
            if SEG.query(0, basho + 1) < basho + 1:
                _, pos = search_lower_bigger(basho, SEG)
                SEG.update(pos, 1)
                res += bigger
            else:
                _, pos = search_upper_bigger(basho, SEG)
                SEG.update(pos, 1)
                res += smaller
        else:  # 右にいたい
            if basho == n - 1:
                _, pos = search_lower_smaller(basho, SEG)
                SEG.update(pos, 1)
                res += smaller
            if SEG.query(basho + 1, n) < n - (basho + 1):
                _, pos = search_upper_smaller(basho, SEG)
                SEG.update(pos, 1)
                res += bigger
            else:
                _, pos = search_lower_smaller(basho, SEG)
                SEG.update(pos, 1)
                res += smaller
    print(res)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)

T = int(input())

# 1-indexed
class BinaryIndexedTree() :
  def __init__(self, n) :
    self.n = n
    self.tree = [0] * (n + 1)
      
  def sum(self, i) :
    s = 0
    while i > 0 :
      s += self.tree[i]
      i -= i & -i
    return s
      
  def add(self, i, x) :
    while i <= self.n :
      self.tree[i] += x
      i += i & -i

for _ in range(T) :
  N = int(input())
  schedule = []
  for i in range(N) :
    K, L, R = map(int, input().split())
    schedule.append((L, K, 0, i))
    schedule.append((R, K, 1, i))
  schedule.sort(reverse=True)
  
  ret = 0
  BIT = BinaryIndexedTree(N)
  visited = set()
  for v, k, t, i in schedule :
    if i in visited :
      continue
    if t == 0 :
      if BIT.sum(k) < k :
        BIT.add(k, 1)
        visited.add(i)
        ret += v
    if t == 1 :
      if BIT.sum(N) - BIT.sum(k) < k :
        BIT.add(k + 1, 1)
        visited.add(i)
        ret += v
  print(ret)

Submission status: Wrong Answer

Solution code:
def solve():
  n = int(input())
  a = [-float("inf") for _ in range(n+1)]
  b = [0 for _ in range(n+1)]
  c = [0 for _ in range(n+1)]
  for _ in range(n):
    k,l,r = map(int,input().split())
    c[k] += 1
    if a[k] == -float("inf"):
      a[k] = l-r
    else:
      if l-r > a[k]:
        a[k] = l-r
    b[k] += r
  s = sum(b)
  e = 0
  f = 0
  m1 = -float("inf")
  m2 = float("inf")
  for i in range(1,n+1):
    if a[i] != -float("inf"):
      if a[i] < 0:
        e += c[i]
        f += 1
        if a[i] > m1:
          m1 = a[i]
      else:
        if m2 > a[i]:
          m2 = a[i] 
    else:
      f += 1
  print(e,f,m1,m2)
  if e >= f:
    for i in range(1,n+1):
       if a[i] >= 0:
          s += b[i]
    print(s)
    if m1+m2 <= 0:
      s -= m2
    else:
      s += m1
  else:
    for i in range(1,n+1):
      if a[i] >= 0:
        s += b[i]
    print(s)
t = int(input())
for _ in range(t):
  solve()

Submission status: Wrong Answer

Solution code:
t=int(input())

for i in range(t):
  ans=0
  n=int(input())
  for j in range(n):
    k,l,r = map(int, input().split())
    ans+=max(l,r)
  print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


t = int(input())
val = [None]*t
from collections import defaultdict
for iii in range(t):
    n = int(input())
    lr = [None]*n
    d1 = defaultdict(list)
    d0 = defaultdict(list)
    for i in range(n):
        k,l,r = list(map(int, input().split()))
        lr[i] = (l - r, -k, l, r)
        if l-r>=0:
            d1[k].append((l-r, l, r, i))
        else:
            d0[k].append((l-r, l, r, i))
            
    
    sl = set()
    sr = set()
#     for i, (v, kk,_,_) in enumerate(lr):
    for kk in range(1, n+1):
        if not kk in d1:
            continue
        ll = d1[kk]
        ll.sort(reverse=True)
        for _, l, r, i in ll:
            if len(sl)<kk:
                sl.add(i)
            else:
                sr.add(i)
    for kk in range(n, 0, -1):
        if not kk in d0:
            continue
        ll = d0[kk]
        ll.sort()
        for _, l, r, i in ll:
            if len(sr)<(n-kk):
                sr.add(i)
            else:
                sl.add(i)
    ans = 0
    for i in sl:
        ans += lr[i][-2]
    for i in sr:
        ans += lr[i][-1]
    val[iii] = ans
write("\n".join(map(str, val)))

Submission status: Wrong Answer

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

def main():
    t = int(input())
    for i in range(t):
        n = int(input())
        ans = 0
        judge_f = [[] for _ in range(n)]
        judge_b = [[] for _ in range(n)]
        for j in range(n):
            k, l, r = map(int, input().split())
            ans += min(l, r)
            if r < l:
                judge_b[k-1].append(l-r)
            elif l < r:
                if k != n:
                    judge_f[k].append(r-l)
        plus = [0]*n
        minus = [0]*n
        key = []
        heapq.heapify(key)
        for j in range(n):
            if judge_b[j]:
                for v in judge_b[j]:
                    heapq.heappush(key, -v)
            if key:
                minus[j] = -heapq.heappop(key)
        key = []
        heapq.heapify(key)
        for j in range(n-1, -1, -1):
            if judge_f[j]:
                for v in judge_f[j]:
                    heapq.heappush(key, -v)
            if key:
                plus[j] = -heapq.heappop(key)
        for i in range(1, n):
            plus[i] += plus[i-1]
            minus[n-i-1] += minus[n-i]
        
        count = 0
        for i in range(n):
            if count < plus[i]+minus[i]:
                count = plus[i]+minus[i]
        print(ans+count)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
t = int(input())
for i in range(t):
    n = int(input())
    a1 = []
    a2 = []
    ans = 0
    flag = [False] * n
    for j in range(n):
        k, l, r = map(int, input().split())
        if l > r:
            a1.append([k, l, r])
        elif l < r:
            a2.append([k, r, l])
        else:
            ans += l
    a1.sort(key = lambda x: x[1] - x[2], reverse = True)
    a2.sort(key = lambda x: x[1] - x[2], reverse = True)
    for j in range(len(a1)):
        num = a1[j][0] - 1
        while num >= 0:
            if flag[num] == False:
                flag[num] = True
                ans += a1[j][1]
                break
            else:
                num -= 1
        else:
            ans += a1[j][2]
    for j in range(len(a2)):
        num = a2[j][0] - 1
        while num <= n - 2:
            if flag[num] == False:
                flag[num] = True
                ans += a2[j][1]
                break
            else:
                num += 1
        else:
            ans += a2[j][2]
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegAccumCalc:
    def __init__(self, value, N=0, calc=lambda x,y: x+y):
        M = max(len(value),N)
        N = 2**(len(bin(M))-3)
        if N < M: N *= 2
        self.N = N
        self.node = [None] * (2*N-1)
        for i, v in enumerate(value):
            self.node[i+N-1] = v
        self.calc = lambda x, y: x if y is None else y if x is None else calc(x,y)
        for i in range(N-2,-1,-1):
            left, right = self.node[2*i+1], self.node[2*i+2]
            self.node[i] = self.calc(left, right)

    def update(self, n, v):
        i = (self.N-1) + n
        self.node[i] = v
        while i > 0:
            i = (i-1)//2
            left, right = self.node[2*i+1], self.node[2*i+2]
            new = self.calc(left,right)
            if self.node[i] == new:
                break
            else:
                self.node[i] = new
    
    def at(self, n):
        return self.node[(self.N-1)+n]

    def query(self, l=0, r=-1):
        if r < 0: r = self.N
        L = l + self.N; R = r + self.N
        s = None
        while L < R:
            if R & 1:
                R -= 1
                s = self.calc(self.node[R-1], s)
            if L & 1:
                s = self.calc(self.node[L-1], s)
                L += 1
            L >>= 1; R >>= 1
        return s

inpl = lambda: list(map(int,input().split()))
T = int(input())
for t in range(T):
    N = int(input())
    base = 0
    KD = []
    for i in range(N):
        K, L, R = inpl()
        base += R
        KD.append((K, L-R))
    KD.sort(key=lambda x: x[1], reverse=True)
    sac = SegAccumCalc([0]*N)
    score = base
    for i in range(N):
        K, D = KD[i]
        if sac.query(0,K) < K:
            sac.update(K-1,sac.at(K-1)+1)
            score += D
    print(score)

Submission status: Wrong Answer

Solution code:
import numpy as np
t = int(input())

ans_li = []
for _ in range(t):

  n = int(input())
  left = []
  right = []
  m_value = []
  ans = 0
  l_cnt = 0
  r_cnt = 0
  for i in range(n):
    k,l,r = map(int, input().split())
    if l > r:
      left.append([k,1/(l-r),l,r])
    elif l < r:
      right.append([n-k,1/(r-l),r,l])
    else:
      m_value.append(l)

  left_sorted = sorted(left, key= lambda x: (x[0],x[1]))
  right_sorted = sorted(right, key= lambda x: (x[0],x[1]))

  for l in left_sorted:
    if l_cnt <= l[0]:
      ans += l[2]
    else:
      ans += l[3]

    l_cnt += 1

  for r in right_sorted:
    if r_cnt < r[0]:
      ans += r[2]
    else:
      ans += r[3]

    r_cnt += 1

  ans += sum(m_value)

  ans_li.append(ans)

for i in ans_li:
  print(i)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()

ans = []

def solve():
    n = int(input())

    klr = [[0 for _ in range(4)] for _ in range(n)]
    groups = [[] for _ in range(3)]
    for i in range(n):
        k, l, r = map(int, input().split())
        klr[i][0] = k; klr[i][1] = l; klr[i][2] = r;
        score = l - r
        if score == 0:
            groups[1].append([score, k, l, r])
        elif score < 0:
            groups[2].append([score, k, l, r])
        else:
            groups[0].append([score, k, l, r])
    # pos, eq, neg
    groups[0] = sorted(groups[0], key=lambda x: (-x[1], x[0]))
    groups[1] = sorted(groups[0], key=lambda x: x[1], reverse=True)

    # 後ろから埋めていく
    out = 0
    for i, day in enumerate(reversed(range(1, len(groups[0])+1))):
        if groups[0][i][1] <= day:
            out += groups[0][i][2]
        else:
            out += groups[0][i][3]
    for i in range(len(groups[1])):
        out += groups[1][i][2]
    day = len(groups[0]) + len(groups[1])
    for i in range(len(groups[2])):
        if groups[2][i][1] <= day:
            out += groups[2][i][2]
        else:
            out += groups[2][i][3]
        day += 1
    return out


t = int(input())
for _ in range(t):
    ans.append(str(solve()))
print("\n".join(ans))

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

t = ni()

for _ in range(t):
    n = ni()
    a = []
    for i in range(n):
        k,l,r = na()
        a.append((abs(l-r),k,l,r))
    a.sort(reverse=True)
    g = [0]*n
    ans = 0
    for _, k,l,r in a:
        if l == r:
            ans+=l
            continue
        elif l > r:
            kk = k-1
            while kk >= 0:
                if g[kk] == 0:
                    g[kk] = l
                    break
                kk -= 1
            else:
                ans += r
        else:
            kk = k
            while kk < n:
                if g[kk] == 0:
                    g[kk] = r
                    break
                kk += 1
            else:
                ans += l
    ans += sum(g)
    print(ans)

Submission status: Wrong Answer

Solution code:
T = int(input())
for _ in range(T):
    N = int(input())
    favdic_l = {}
    favdic_r = {}
    total = 0
    for i in range(N):
        K, L, R = map(int, input().split())
        if L > R:
            favdic_l.setdefault(K, [])
            favdic_l[K].append(L-R)
            total += R
        else:
            favdic_r.setdefault(N-K, [])
            favdic_r[N-K].append(R-L)
            total += L

    for dic in [favdic_l, favdic_r]:
        c_count = 0
        dic = sorted(dic.items())
        for k, v in dic:
            space = k - c_count
            c_count += len(v)
            if space > 0:
                total += sum(v[-space:])
    print(total)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:


# point update
# range query
class SegmentTreeNode:
	def __init__(self, start, end, initial, merge):
#		print("s", start, end)
		self.start = start
		self.end = end
		self.width = end - start
		self.merge = merge
		self.initial = initial
		if self.width > 1:
			w2 = self.width // 2
			self.left = SegmentTreeNode(start, start + w2, initial, merge)
			self.right = SegmentTreeNode(start + w2, end, initial, merge)
			self.value = self.merge(self.left.value, self.right.value)
		else:
			self.value = self.initial

	def update(self, index, value):
		if self.start <= index and index < self.end:
			if self.width == 1:
				self.value = value
			else:
				self.left.update(index, value)
				self.right.update(index, value)
				self.value = self.merge(self.left.value, self.right.value)
	
	def pick(self, start, end):
		if start <= self.start and self.end <= end:
			return self.value
		elif self.start < end and self.end > start:
#			m = self.merge(self.left.pick(start, end), self.right.pick(start, end))
#			print(start, end, m)
			return self.merge(self.left.pick(start, end), self.right.pick(start, end))
		else:
			return self.initial
	
	def to_list(self, items):
		if self.width == 1:
			items.append(self.value)
		else:
			self.left.to_list(items)
			self.right.to_list(items)
	
class SegmentTree:
	def __init__(self, n, *, merge, initial = None):
		width = 1
		while width < n:
			width *= 2
		self.root = SegmentTreeNode(0, width, initial, merge)
		self.root.value = 0
		self.capacity = width
	
	def update(self, index, value):
		self.root.update(index, value)
	
	def pick(self, start, end):
		return self.root.pick(start, end)
	
	def to_list(self):
		items = []
		self.root.to_list(items)
		return items
	

def merge_r(l, r):
	if r == None:
		return l
	elif l == None:
		return r
	elif r[1] == None:
		return r
	else:
		return l

def merge_l(l, r):
	if r == None:
		return l
	elif l == None:
		return r
	elif l[1] == None:
		return l
	else:
		return r

T = int(input())

for t in range(T):
	N = int(input())
	
	camels = []
	
	for _ in range(N):
		K, L, R = map(int, input().split())
		camels.append((abs(L - R), L, R, K))
	
	camels.sort()
	camels.reverse()
	
	width = 1
	while width < N:
		width *= 2
	st_l = SegmentTree(N, merge = merge_l)
	st_r = SegmentTree(N, merge = merge_r)
	
	for i in range(N):
		st_l.update(i, (i, None))
		st_r.update(i, (i, None))
	
	for i in range(N + 1, width):
		st_l.update(i, (i, -1))
		st_r.update(i, (i, -1))
	
	total = 0
	for D, L, R, K in camels:
		if L > R:
			i, c = st_r.pick(0, K)
#			print(L, R, i)
			if c == None:
#				print("x", i, R)
				st_r.update(i, (i, c))
				st_l.update(i, (i, c))
				total += L
			else:
				total += R
		else:
			pair = st_l.pick(K, N)
			if pair == None:
				total += L
			else:
				i, c = pair
#				print(L, R, i)
				if c == None:
#					print("x", i, R)
					st_r.update(i, (i, c))
					st_l.update(i, (i, c))
					total += R
				else:
					total += L
	print(total)

Submission status: Wrong Answer

Solution code:
t=int(input())
ans=0
for i in range(t):
  n=int(input())
  for j in range(n):
    k,l,r = map(int, input().split())
    ans+=max(l,r)
print(ans)