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.

Solution in Rust (1.42.0) (judge verdict: Wrong Answer)

#![allow(unused_imports)]
#![allow(non_snake_case, unused)]

use std::cmp::*;
use std::collections::*;
use std::ops::*;

// https://atcoder.jp/contests/hokudai-hitachi2019-1/submissions/10518254

macro_rules! eprint {
    ($($t:tt)*) => {{
        use ::std::io::Write;
        let _ = write!(::std::io::stderr(), $($t)*);
    }};
}
macro_rules! eprintln {
    () => { eprintln!(""); };
    ($($t:tt)*) => {{
        use ::std::io::Write;
        let _ = writeln!(::std::io::stderr(), $($t)*);
    }};
}
macro_rules! dbg {
    ($v:expr) => {{
        let val = $v;
        eprintln!("[{}:{}] {} = {:?}", file!(), line!(), stringify!($v), val);
        val
    }}
}

macro_rules! mat {
    ($($e:expr),*) => { Vec::from(vec![$($e),*]) };
    ($($e:expr,)*) => { Vec::from(vec![$($e),*]) };
    ($e:expr; $d:expr) => { Vec::from(vec![$e; $d]) };
    ($e:expr; $d:expr $(; $ds:expr)+) => { Vec::from(vec![mat![$e $(; $ds)*]; $d]) };
}

macro_rules! ok {
    ($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => {
        $a$([$i])*.$f($($t),*)
    };
    ($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { {
        let t = $e;
        ok!($a$([$i])*.$f($($es),*)$(@$t)*@t)
    } };
}

pub fn readln() -> String {
    let mut line = String::new();
    ::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!("{}", e));
    line
}

macro_rules! read {
    ($($t:tt),*; $n:expr) => {{
        let stdin = ::std::io::stdin();
        let ret = ::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {
            let line = line.unwrap();
            let mut it = line.split_whitespace();
            _read!(it; $($t),*)
        }).collect::<Vec<_>>();
        ret
    }};
    ($($t:tt),*) => {{
        let line = readln();
        let mut it = line.split_whitespace();
        _read!(it; $($t),*)
    }};
}

macro_rules! _read {
    ($it:ident; [char]) => {
        _read!($it; String).chars().collect::<Vec<_>>()
    };
    ($it:ident; [u8]) => {
        Vec::from(_read!($it; String).into_bytes())
    };
    ($it:ident; usize1) => {
        $it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1
    };
    ($it:ident; [usize1]) => {
        $it.map(|s| s.parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1).collect::<Vec<_>>()
    };
    ($it:ident; [$t:ty]) => {
        $it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!("{}", e))).collect::<Vec<_>>()
    };
    ($it:ident; $t:ty) => {
        $it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<$t>().unwrap_or_else(|e| panic!("{}", e))
    };
    ($it:ident; $($t:tt),+) => {
        ($(_read!($it; $t)),*)
    };
}


pub fn main() {
    let _ = ::std::thread::Builder::new().name("run".to_string()).stack_size(32 * 1024 * 1024).spawn(run).unwrap().join();
}

const MOD: usize = 1_000_000_007;
const INF: i32 = std::i32::MAX;

pub trait TE {
    type T: Clone;
    type E: Clone;
    fn fold(l: Self::T, r: Self::T) -> Self::T;
    fn eval(p: Self::T, x: Self::E) -> Self::T;
    fn merge(f: Self::E, g: Self::E) -> Self::E;
    fn e() -> Self::T;
    fn id() -> Self::E;
}

pub struct LazySegmentTree<R: TE> {
    size: usize,
    bit: usize,
    a: Vec<(R::T, R::E)>,
}

impl <R: TE> LazySegmentTree<R> {
    pub fn new(n: usize) -> LazySegmentTree<R> {
        let mut bit = 0;
        while (1 << bit) < n {
            bit += 1;
        }
        LazySegmentTree {
            size: 1 << bit,
            bit: bit,
            a: vec![(R::e(), R::id()); 2 << bit],
        }
    }
    pub fn build_by(z: &[R::T]) -> LazySegmentTree<R> {
        let n = z.len();
        let mut bit = 0;
        while (1 << bit) < n {
            bit += 1;
        }
        let mut a = vec![(R::e(), R::id()); 2 << bit];
        for (a, z) in a[(1 << bit)..].iter_mut().zip(z.iter()) {
            a.0 = z.clone();
        }
        for i in (1..(1 << bit)).rev() {
            let l = R::eval(a[2 * i].0.clone(), a[2 * i].1.clone());
            let r = R::eval(a[2 * i + 1].0.clone(), a[2 * i + 1].1.clone());
            a[i].0 = R::fold(l, r);
        }
        LazySegmentTree {
            size: 1 << bit,
            bit : bit,
            a: a,
        }
    }
    fn eval(&self, k: usize) -> R::T {
        R::eval(self.a[k].0.clone(), self.a[k].1.clone())
    }
    fn propagate(&mut self, x: usize) {
        let x = x + self.size;
        for i in (1..(self.bit + 1)).rev() {
            let k = x >> i;
            self.a[2 * k].1 = R::merge(self.a[2 * k].1.clone(), self.a[k].1.clone());
            self.a[2 * k + 1].1 = R::merge(self.a[2 * k + 1].1.clone(), self.a[k].1.clone());
            self.a[k].1 = R::id();
            self.a[k].0 = R::fold(self.eval(2 * k), self.eval(2 * k + 1));
        }
    }
    fn save(&mut self, x: usize) {
        let x = x + self.size;
        for i in 1..(self.bit + 1) {
            let k = x >> i;
            self.a[k].0 = R::fold(self.eval(2 * k), self.eval(2 * k + 1));
        }
    }
    pub fn update(&mut self, l: usize, r: usize, op: R::E) {
        self.propagate(l);
        self.propagate(r - 1);
        let mut x = l + self.size;
        let mut y = r + self.size;
        while x < y {
            if x & 1 == 1 {
                self.a[x].1 = R::merge(self.a[x].1.clone(), op.clone());
                x += 1;
            }
            if y & 1 == 1 {
                y -= 1;
                self.a[y].1 = R::merge(self.a[y].1.clone(), op.clone());
            }
            x >>= 1;
            y >>= 1;
        }
        self.save(l);
        self.save(r - 1);
    }
    pub fn find(&mut self, l: usize, r: usize) -> R::T {
        self.propagate(l);
        self.propagate(r - 1);
        let mut x = l + self.size;
        let mut y = r + self.size;
        let mut p = R::e();
        let mut q = R::e();
        while x < y {
            if x & 1 == 1 {
                p = R::fold(p, self.eval(x));
                x += 1;
            }
            if y & 1 == 1 {
                y -= 1;
                q = R::fold(self.eval(y), q);
            }
            x >>= 1;
            y >>= 1;
        }
        R::fold(p, q)
    }
}

struct R;
impl TE for R {
    type T = (usize, usize);
    type E = usize;
    fn fold(l: Self::T, r: Self::T) -> Self::T {
        if l.0==0 && r.0==0 {
            (0,min(l.1,r.1))
        }
        else if r.0==0 {
            (0,r.1)
        }
        else if l.0==0 {
            (0,l.1)
        }
        else {
            (1,l.1)
        }
    }
    fn eval(p: Self::T, x: Self::E) -> Self::T {
        if x == 0 {
            (p.0, p.1)
        } else {
            (1, p.1)
        }
 
    }
    fn merge(f: Self::E, g: Self::E) -> Self::E {
        f+g
    }
    fn e() -> Self::T {
        (1, 0)
    }
    fn id() -> Self::E {
        0
    }
}

struct R2;
impl TE for R2 {
    type T = (usize, usize);
    type E = usize;
    fn fold(l: Self::T, r: Self::T) -> Self::T {
        if l.0==0 && r.0==0 {
            (0, max(l.0,r.0))
        }
        else if l.0==0 {
            (0,l.1)
        }
        else if r.0==0 {
            (0,r.1)
        }
        else {
            (1,r.1)
        }
    }
    fn eval(p: Self::T, x: Self::E) -> Self::T {
        if x == 0 {
            (p.0, p.1)
        } else {
            (1, p.1)
        }
 
    }
    fn merge(f: Self::E, g: Self::E) -> Self::E {
        f+g
    }
    fn e() -> Self::T {
        (1, 0)
    }
    fn id() -> Self::E {
        0
    }
}

fn solve() {
    let t = read!(usize);
    for i in 0..t {
        let n = read!(usize);
        let klr = read!([i64];n);
        let mut v = vec![];
        let mut mid = 0;
        for j in 0..n {
            let k = (klr[j][0]-1) as usize;
            let l = klr[j][1];
            let r = klr[j][2];
            v.push((l-r,k,l,r));
            if l>=r {
                mid += 1;
            }
        }
        let mut a = vec![(0,0);n];
        for j in 0..n {
            a[j] = (0,j);
        }
        let mut s = LazySegmentTree::<R>::build_by(a.as_slice());
        let mut s2 = LazySegmentTree::<R2>::build_by(a.as_slice());
        v.sort_by(|a, b| b.cmp(a));
        let mut ans = 0;
        for j in 0..n {
            let d = v[j].0;
            let k = v[j].1;
            let l = v[j].2;
            let r = v[j].3;
            if l>=r {
                let lidx = 0;
                let ridx = k+1;
                let x = s.find(lidx,ridx);
                if x.0==0 {
                    ans += l;
                    s.update(x.1,x.1+1,1);
                }
                else {
                    let x = s.find(lidx,mid);
                    ans += r;
                    s.update(x.1,x.1+1,1);
                    // println!("{} {} {}",lidx,mid,x.1);
                }
                // for k in 0..n {
                //     print!("{} ",s.find(k,k+1).0);
                // }
                // print!("{} ",ans);
                // println!();
            }
        }
        v.sort_by(|a, b| a.cmp(b));
        for j in 0..n {
            let d = v[j].0;
            let k = v[j].1;
            let l = v[j].2;
            let r = v[j].3;
            if r>l {
                let lidx = k+1;
                let ridx = n;
                let x = s2.find(max(mid,lidx),ridx);
                if x.0==0 {
                    ans += r;
                    s2.update(x.1,x.1+1,1);
                }
                else {
                    let x = s2.find(mid,n);
                    ans += l;
                    s2.update(x.1,x.1+1,1);
                }
                // for k in 0..n {
                //     print!("{} ",s2.find(k,k+1).0);
                // }
                // print!("{} ",ans);
                // println!();
            }
        }
        println!("{}",ans);
    }
}

fn run() {
    solve();
}