I=input
for _ in[0]*int(I()):
 n,k=map(int,I().split());a=sorted(map(len,I().strip('L').split('W')));m=len(a)+k
 while a and a[0]<=k:k-=a.pop(0)
 print((2*min(n,m-1)-len(a)or 1)-1)


#   ==========     //\\       //||     ||====//||
#       ||        //  \\        ||     ||   // ||
#       ||       //====\\       ||     ||  //  ||
#       ||      //      \\      ||     || //   ||
#   ========== //        \\  ========  ||//====||
#  code

def solve():
    n, m = map(int, input().split())
    s = input()
    s = s[:n]

    p = 0
    gaps = []
    points = 0
    lastsect = 0
    firstsect = 0
    wins = len(list(filter(lambda x : x == 'W', s)))

    if wins == 0:
        m = min(m, n)
        if m == 0:
            print(0)
        else:
            print(2 * m - 1)
        return

    if m + wins >= n:
        print(2 * n - 1)
        return

    i = 0
    while i < n and s[i] == 'L':
        i += 1

    firstsect = i

    for j, v in enumerate(s[i:]):
        if v == 'L':
            p += 1
        else:
            if p > 0:
                gaps.append(p)
                p = 0
            points += 1 + (1 if (j + i > 0 and s[j + i - 1] == 'W') else 0)

    if p > 0:
        lastsect = p

    gaps.sort()
    # print(gaps, points)
    i = 0
    k = m
    while i < len(gaps) and k > 0:
        if gaps[i] > k:
            points += 2 * k
            k = 0
        else:
            points += 2 * gaps[i] + 1
            k -= gaps[i]
        i += 1

    points += 2 * min(k, firstsect)
    k -= min(k, firstsect)
    points += 2 * min(k, lastsect)

    print(points)

def main():
    t = 1
    t = int(input())
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()


#   ==========     //\\       //||     ||====//||
#       ||        //  \\        ||     ||   // ||
#       ||       //====\\       ||     ||  //  ||
#       ||      //      \\      ||     || //   ||
#   ========== //        \\  ========  ||//====||
#  code

def solve():
    n, m = map(int, input().split())
    s = input()
    s = s[:n]

    p = 0
    gaps = []
    points = 0
    lastsect = 0
    firstsect = 0
    wins = len(list(filter(lambda x : x == 'W', s)))

    if wins == 0:
        m = min(m, n)
        print(2 * m - 1)
        return

    if m + wins >= n:
        print(2 * n - 1)
        return

    i = 0
    while i < n and s[i] == 'L':
        i += 1

    firstsect = i

    for j, v in enumerate(s[i:]):
        if v == 'L':
            p += 1
        else:
            if p > 0:
                gaps.append(p)
                p = 0
            points += 1 + (1 if (j + i > 0 and s[j + i - 1] == 'W') else 0)

    if p > 0:
        lastsect = p

    gaps.sort()
    # print(gaps, points)
    i = 0
    k = m
    while i < len(gaps) and k > 0:
        if gaps[i] > k:
            points += 2 * k
            k = 0
        else:
            points += 2 * gaps[i] + 1
            k -= gaps[i]
        i += 1

    points += 2 * min(k, firstsect)
    k -= min(k, firstsect)
    points += 2 * min(k, lastsect)

    print(points)

def main():
    t = 1
    t = int(input())
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()


#   ==========     //\\       //||     ||====//||
#       ||        //  \\        ||     ||   // ||
#       ||       //====\\       ||     ||  //  ||
#       ||      //      \\      ||     || //   ||
#   ========== //        \\  ========  ||//====||
#  code

def solve():
    n, m = map(int, input().split())
    s = input()
    s = s[:n]

    p = 0
    gaps = []
    points = 0
    lastsect = 0
    firstsect = 0
    wins = len(list(filter(lambda x : x == 'W', s)))

    i = 0
    while i < n and s[i] == 'L':
        i += 1

    firstsect = i

    for j, v in enumerate(s[i:]):
        if v == 'L':
            p += 1
        else:
            if p > 0:
                gaps.append(p)
                p = 0
            points += 1 + (1 if (j + i > 0 and s[j + i - 1] == 'W') else 0)

    if p > 0:
        lastsect = p

    if m + wins >= n:
        print(2 * n - 1)
        return

    gaps.sort()
    # print(gaps, points)
    i = 0
    k = m
    while i < len(gaps) and k > 0:
        if gaps[i] > k:
            points += 2 * k
            k = 0
        else:
            points += 2 * gaps[i] + 1
            k -= gaps[i]
        i += 1

    points += 2 * min(k, firstsect)
    k -= min(k, firstsect)
    points += 2 * min(k, lastsect)

    print(points)

def main():
    t = 1
    t = int(input())
    for _ in range(t):
        solve()

if __name__ == "__main__":
    main()


import heapq
import collections
from math import log2
import itertools
from functools import lru_cache
from sys import setrecursionlimit as srl
srl(2*10**6)
N = 200001

def amin(a,b):
    if b < a:
        a = b
    return a
def solve(n,k,a):
    w = 0
    W = 0
    ans = 0
    v = []
    cur = 0
    for i in range(n):
        if a[i] == 'W':
            if cur:
                v.append(cur)
                cur = 0
            w +=1
            ans+=1
            if W:
                ans+=1
            W = 1
        else:
            W = 0
            if w:
                cur +=1
    if not w:
        return max(2*k-1 ,0)
    if  k > n-w:
        k = n-w
    ans += 2*k
    v.sort()
    for x in v:
        if x <= k:
            ans +=1
            k-=x
    return ans

t = int(input())
for i in range(1,t+1):
    n,k = map(int,input().split())
    a = input()
    print(solve(n,k,a))


t = int(input())
for i in range(t):
   n, m = map(int, input().split())
   s = input()
   scoreinitial = 0
   if s[0] == 'W':
      scoreinitial += 1
   for i in range(1, len(s)):
      if s[i] == 'W' and s[i-1] == 'W':
         scoreinitial += 2
      elif s[i] == 'W':
         scoreinitial += 1
   paq = []
   cuts = s.split('W')
   extr = [len(x) for x in cuts]
   nbL = sum(extr)
   stock = min(m, nbL)
   if stock == 0:
      print(scoreinitial)
   elif nbL < n:
      paq = sorted(extr[1:-1])
      #print(paq)
      rep = 0
      for i in paq:
         if i <= stock and i > 0:
            rep += i*2 + 1
            stock -= i
      rep += 2*stock
      print(rep+scoreinitial)
   else:
      print(stock*2-1)


t=int(input())
for qwe in range(t):
    [n,k]=[int(j) for j in input().split()]
    s=input()
    l=list(s)
    c=0
    a=[]
    if l[0]=="W":
        ans=1
    else:
        ans=0
    for i in range(1,n):
        if l[i]=="W":
            if l[i-1]=="W":
                ans+=2
            else:
                ans+=1
    m=-1
    fl=[]
    for i in range(n):
        if l[i]=="W":
            if m==0 and c>0:
                a.append(c)
            elif c>0:
                fl.append(c)
            c=0
            m=0
        else:
            c+=1
    fl.append(c)
    a.sort()
    for j in a:
        if k>=j:
            ans+=(2*j+1)
            k-=j
        else:
            ans+=2*k
            k=0
    if ans==0:
        ans=max(2*k-1,0)
    else:
        ans+=2*(min(sum(fl),k))
    print(ans)


# cook your dish here
#hi
import math
import os
import random
import re
import sys
def maxpts(str1,k):
    w=0
    losses=[]
    ans=0
    W=False
    cur=0
    for c in str1:
        if c=='W':
            if cur:
                losses.append(cur)
                cur=0
            w+=1
            ans+=1
            if W:
                ans+=1
            W=True
        else:
            W=False
            if w:
                cur+=1

    if w==0:
        print(max(2*k-1,0))
        return

    n=len(str1)
    if k>=n-w:
        print(n*2-1)
        return
    ans+=2*k
    losses.sort()

    for l1 in losses:
        if k>=l1:
            ans+=1
            k=k-l1
        else:
            break
    print(ans)

if __name__=='__main__':
    n=int(input())
    for i in range(n):
        n1,k=map(int,input().rstrip().split())
        str1=input()
        maxpts(str1,k)


# cook your dish here
import math
import os
import random
import re
import sys
def maxpts(str1,k):
    w=0
    losses=[]
    for c in str1:
        if c=='W':
            w+=1
    if w==0:
        print(max(2*k-1,0))
        return

    l=0
    for c in str1:
        if c=='L':
            l+=1
        else:
            if l!=0:
                losses.append(l)
            l=0
    w+=k
    if w>len(str1):
        print(2*len(str1)-1)
        return
    losses.sort()
    l=0
    if str1[0]=='L':
        for c in str1:
            if c=='L':
                l+=1
            else:
                break
        losses.remove(l)
    l=0

    sp=0
    i=0
    for i in range(len(losses)):
        if sp+losses[i]>k:
            break
        sp+=losses[i]
    wl=len(losses)-i
    if wl==1 and k>sp and str1[-1]=='L':
        wl=0
    #print(k,w,wl)
    print(2*w-1-wl)

if __name__=='__main__':
    n=int(input())
    for i in range(n):
        n1,k=map(int,input().rstrip().split())
        str1=input()
        maxpts(str1,k)


# cook your dish here
import math
import os
import random
import re
import sys
def maxpts(str1,k):
    w=0
    losses=[]
    ans=0
    W=False
    cur=0
    for c in str1:
        if c=='W':
            if cur:
                losses.append(cur)
                cur=0
            w+=1
            ans+=1
            if W:
                ans+=1
            W=True
        else:
            W=False
            if w:
                cur+=1

    if w==0:
        print(max(2*k-1,0))
        return

    n=len(str1)
    if k>=n-w:
        print(n*2-1)
        return
    ans+=2*k
    losses.sort()

    for l1 in losses:
        if k>=l1:
            ans+=1
            k=k-l1
        else:
            break
    print(ans)

if __name__=='__main__':
    n=int(input())
    for i in range(n):
        n1,k=map(int,input().rstrip().split())
        str1=input()
        maxpts(str1,k)


# cook your dish here
import math
import os
import random
import re
import sys
def maxpts(str1,k):
    w=0
    losses=[]
    for c in str1:
        if c=='W':
            w+=1
    if w==0:
        print(max(2*k-1,0))
        return

    l=0
    for c in str1:
        if c=='L':
            l+=1
        else:
            if l!=0:
                losses.append(l)
            l=0
    ans=0
    prev=False
    for c in str1:
        if c=='W':
            if prev:
                ans+=2
            else:
                ans+=1
            prev=True
        else:
            prev=False
    n=len(str1)
    if k>=n-w:
        print(n*2-1)
        return
    ans+=2*k
    losses.sort()
   # print(losses)
    for l1 in losses:
        if k>=l1:
            ans+=1
            k=k-l1
        else:
            break
    print(ans)

if __name__=='__main__':
    n=int(input())
    for i in range(n):
        n1,k=map(int,input().rstrip().split())
        str1=input()
        maxpts(str1,k)


T = int(input())
for _ in range(T):
    n, k = map(int, input().split())
    s = input()
    res = 0
    gaps=[]
    gap0=0
    gap = 0
    prev = False
    f = True
    for x in s:
        if f:
            if x == 'L':
                gap0 += 1
            else:
                f = False
                res = 1
                prev = True
        else:
            if x == 'L':
                gap += 1
                prev = False
            else:
                res += 1
                if prev:
                    res += 1
                else:
                    gaps.append(gap)
                    gap = 0
                prev = True
    if prev:
        gapN = 0
    else:
        gapN = gap
    gaps.sort()
    nn = len(gaps)
    i = 0
    while i < nn and k >= gaps[i]:
        res += 2*gaps[i] + 1
        k -= gaps[i]
        i += 1
    if i < nn or k <= gap0 + gap:
        res += 2*k
    else:
        res += (gap0+gap)*2
    if gap0 == n and k>0:
        res -= 1
    print(res)


class Streak:
    def __init__(self, start_ind, end_ind):
        self.start_ind = start_ind
        self.end_ind = end_ind

class StreakNbors:
    def __init__(self, streak_a, streak_b):
        self.streak_a = streak_a
        self.streak_b = streak_b

    def get_gap(self):
        return (self.streak_b.start_ind - self.streak_a.end_ind) - 1

    def close_gap(self):
        self.streak_a.end_ind += 1

t = int(input())
for it in range(0, t):
    n, k = tuple(list(map(int, input().split(' '))))
    results = [char for char in input()]

    if n == 1:
        if k >= 1:
            results[0] = 'W'
    else:
        streak_list = []
        current_streak = None
        for i in range(0, len(results)):
            if results[i] == 'W':
                if i == 0 or results[i - 1] == 'L':
                    current_streak = Streak(i, i)
                    streak_list.append(current_streak)
                else:
                    current_streak.end_ind = i

        streak_nbors_list = []
        for i in range(0, len(streak_list) - 1):
            streak_nbors_list.append(StreakNbors(streak_list[i], streak_list[i + 1]))

        streak_nbors_list = sorted(streak_nbors_list, key=lambda streak_nbors: streak_nbors.get_gap())

        streak_nbors_ind = 0
        changes = 0
        while changes < k and streak_nbors_ind < len(streak_nbors_list):
            current_streak_nbors = streak_nbors_list[streak_nbors_ind]
            if current_streak_nbors.get_gap() > 0:
                current_streak_nbors.close_gap()
                changes += 1
            else:
                streak_nbors_ind += 1

        for i in range(0, len(streak_nbors_list)):
            current_streak_nbors = streak_nbors_list[i]
            streak_a_start_ind = current_streak_nbors.streak_a.start_ind
            streak_a_end_ind = current_streak_nbors.streak_a.end_ind
            for j in range(streak_a_start_ind, streak_a_end_ind + 1):
                results[j] = 'W'

            streak_b_start_ind = current_streak_nbors.streak_b.start_ind
            streak_b_end_ind = current_streak_nbors.streak_b.end_ind
            for j in range(streak_b_start_ind, streak_b_end_ind + 1):
                results[j] = 'W'

        min_streak_ind = 200001
        max_streak_ind = -1

        for i in range(0, len(results)):
            if results[i] == 'W':
                min_streak_ind = min(i, min_streak_ind)
                max_streak_ind = max(i, min_streak_ind)

        while changes < k:
            if min_streak_ind > 0:
                min_streak_ind -= 1
                results[min_streak_ind] = 'W'
                changes +=1
            elif max_streak_ind < len(results) - 1:
                max_streak_ind += 1
                results[max_streak_ind] = 'W'
                changes += 1
            else:
                break

    score = 0
    for i in range(0, n):
        if results[i] == 'W':
            score += 1
            if i > 0 and results[i - 1] == 'W':
                score += 1

    print(score)


def calculate_score(results, n):
    score = 0
    for i in range(0, n):
        if results[i] == 'W':
            score += 1
            if i > 0 and results[i - 1] == 'W':
                score += 1
    return score

t = int(input())
for it in range(0, t):
    n, k = tuple(list(map(int, input().split(' '))))
    results = [char for char in input()]

    changes_made = 0
    if changes_made < k:
        for i in range(1, n - 1):
            if results[i] == 'L' and results[i - 1] == 'W' and results[i + 1] == 'W':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break
    if changes_made < k:
        for i in range(0, n):
            left_win_check = i > 0 and results[i] == 'L' and results[i - 1] == 'W'
            right_win_check = i < (n - 1) and results[i] == 'L' and results[i + 1] == 'W'
            if left_win_check or right_win_check:
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break
    if changes_made < k:
        for i in range(0, n):
            if results[i] == 'L':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break

    print(calculate_score(results, n))


t = int(input())

def calculate_score(results, n):
    score = 0
    for i in range(0, n):
        if results[i] == 'W':
            score += 1
            if i > 0 and results[i - 1] == 'W':
                score += 1
    return score

for it in range(0, t):
    n, k = tuple(list(map(int, input().split(' '))))
    results = [char for char in input()]

    changes_made = 0
    if changes_made < k:
        for i in range(1, n - 1):
            if results[i] == 'L' and results[i - 1] == 'W' and results[i + 1] == 'W':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break
    if changes_made < k:
        for i in range(1, n):
            if results[i] == 'L' and results[i - 1] == 'W':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break
    if changes_made < k:
        for i in range(0, n):
            if results[i] == 'L':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break

    print(calculate_score(results, n))


def calculate_score(results, n):
    score = 0
    for i in range(0, n):
        if results[i] == 'W':
            score += 1
            if i > 0 and results[i - 1] == 'W':
                score += 1
    return score

t = int(input())
for it in range(0, t):
    n, k = tuple(list(map(int, input().split(' '))))
    results = [char for char in input()]

    changes_made = 0
    if changes_made < k:
        for i in range(1, n - 1):
            if results[i] == 'L' and results[i - 1] == 'W' and results[i + 1] == 'W':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break
    if changes_made < k:
        for i in range(1, n):
            if results[i] == 'L' and results[i - 1] == 'W':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break
    if changes_made < k:
        for i in range(0, n):
            if results[i] == 'L':
                results[i] = 'W'
                changes_made += 1
                if changes_made == k:
                    break

    print(calculate_score(results, n))


t = int(input())
for it in range(0, t):
    n, k = tuple(list(map(int, input().split(' '))))
    results = [char for char in input()]

    initial_score = 0
    loss_amount = 0

    for i in range(0, len(results)):
        if i > 0 and results[i] == 'W' and results[i - 1] == 'W':
            initial_score += 1
        if results[i] == 'L':
            loss_amount += 1

    k = min(k, loss_amount)
    initial_score += (n - loss_amount)

    streak_increase_added_score = 2 * k

    if loss_amount == n and streak_increase_added_score > 0:
        streak_increase_added_score -= 1

    streak_diffs = []
    current_streak_diff = 0
    streak_found = 0
    for i in range(0, n):
        if results[i] == 'W':
            streak_found = True
            if current_streak_diff != 0:
                streak_diffs.append(current_streak_diff)
                current_streak_diff = 0
        if results[i] == 'L' and streak_found:
            current_streak_diff += 1

    sorted_streak_diffs = sorted(streak_diffs)

    disjoint_streak_decrease_added_score = 0
    for i in range(0, len(sorted_streak_diffs)):
        if k >= sorted_streak_diffs[i]:
            disjoint_streak_decrease_added_score += 1
            k -= sorted_streak_diffs[i]
        else:
            break

    final_score = (initial_score + streak_increase_added_score + disjoint_streak_decrease_added_score)

    print(final_score)


class Streak:
    def __init__(self, start_ind, end_ind):
        self.start_ind = start_ind
        self.end_ind = end_ind

class StreakNbors:
    def __init__(self, streak_a, streak_b):
        self.streak_a = streak_a
        self.streak_b = streak_b

    def get_gap(self):
        return (self.streak_b.start_ind - self.streak_a.end_ind) - 1

    def close_gap(self):
        self.streak_a.end_ind += 1

t = int(input())
for it in range(0, t):
    n, k = tuple(list(map(int, input().split(' '))))
    results = [char for char in input()]

    if n == 1:
        if k >= 1:
            results[0] = 'W'
    else:
        streak_list = []
        current_streak = None
        for i in range(0, len(results)):
            if results[i] == 'W':
                if i == 0 or results[i - 1] == 'L':
                    current_streak = Streak(i, i)
                    streak_list.append(current_streak)
                else:
                    current_streak.end_ind = i

        if streak_list:
            streak_nbors_list = []
            for i in range(0, len(streak_list) - 1):
                streak_nbors_list.append(StreakNbors(streak_list[i], streak_list[i + 1]))

            streak_nbors_list = sorted(streak_nbors_list, key=lambda streak_nbors: streak_nbors.get_gap())

            streak_nbors_ind = 0
            changes = 0
            while changes < k and streak_nbors_ind < len(streak_nbors_list):
                current_streak_nbors = streak_nbors_list[streak_nbors_ind]
                if current_streak_nbors.get_gap() > 0:
                    current_streak_nbors.close_gap()
                    changes += 1
                else:
                    streak_nbors_ind += 1

            for i in range(0, len(streak_nbors_list)):
                current_streak_nbors = streak_nbors_list[i]
                streak_a_start_ind = current_streak_nbors.streak_a.start_ind
                streak_a_end_ind = current_streak_nbors.streak_a.end_ind
                for j in range(streak_a_start_ind, streak_a_end_ind + 1):
                    results[j] = 'W'

                streak_b_start_ind = current_streak_nbors.streak_b.start_ind
                streak_b_end_ind = current_streak_nbors.streak_b.end_ind
                for j in range(streak_b_start_ind, streak_b_end_ind + 1):
                    results[j] = 'W'

            min_streak_ind = 200001
            max_streak_ind = -1

            for i in range(0, len(results)):
                if results[i] == 'W':
                    min_streak_ind = min(i, min_streak_ind)
                    max_streak_ind = max(i, min_streak_ind)

            while changes < k:
                if min_streak_ind > 0:
                    min_streak_ind -= 1
                    results[min_streak_ind] = 'W'
                    changes +=1
                elif max_streak_ind < len(results) - 1:
                    max_streak_ind += 1
                    results[max_streak_ind] = 'W'
                    changes += 1
                else:
                    break
        else:
            for i in range(0, k):
                results[i] = 'W'

    score = 0
    for i in range(0, n):
        if results[i] == 'W':
            score += 1
            if i > 0 and results[i - 1] == 'W':
                score += 1

    print(score)


import sys
import math
from decimal import *
def I(): return int(sys.stdin.readline())
def IL(): return list(map(int,sys.stdin.readline().strip().split()))
def ILS(): return list(map(str,sys.stdin.readline().strip().split()))

def solve():
	tt = I()
	for ii in range(tt):
		n,k = IL()
		ss = input()
		s = [x for x in ss]
		w=0;l=0;
		for i in range(n):
			if(s[i]=='W') : w+=1;
			else : l+=1;

		if(k>=l):
			print((2*n - 1));
			continue;

		ans=0;
		if(s[0]=='W') :
			ans+=1;
		for i in range(1,n):
			if(s[i]=='W'):
				ans+=1;
				if(s[i-1]=='W'):
					ans+=1;

		if(k==0):
			print(ans);
			continue;

		loss = [];
		c=0;idx=n;
		for i in range(n):
			if(s[i]=='W'):
				idx=i;
				break;

		if(idx==n):
			print((k*2)-1);
			continue;
		for i in range(idx,n):

			if(s[i]=='W' and c>0):
				loss.append(c);
				c=0;

			elif(s[i]=='L') : c+=1;

		loss.sort()
		m=len(loss)
		for i in range(m):
			if(k<=0): break;
			if(loss[i]>k):
				ans+=(k*2);
				k=0;

			else:
				ans+=((loss[i]*2)+1);
				k-=loss[i];

		if(k>0):
			ans+=(k*2);

		print(ans);

solve()


# wow, I'm bad

t = int(input())

for _ in range(t):
    n,K = map(int,input().split())
    s = input()

    def way1():
        global n,K,s

        if s.find('W') == -1:
            return max(0, 2*min(K, n) - 1)

        k = K
        score = int(s[0] == 'W')
        for i in range(1, n):
            if s[i-1] == s[i] == 'W':
                score += 2
            elif s[i] == 'W':
                score += 1

        loss_streaks = [len(x) for x in s.split('W') if x != '']
        if s[0] == 'L':
            first = loss_streaks[0]
            del loss_streaks[0]
        else:
            first = 0
        if s[-1] == 'L' and loss_streaks:
            last = loss_streaks[-1]
            del loss_streaks[-1]
        else:
            last = 0

        loss_streaks.sort()
        for i in range(len(loss_streaks)):
            if loss_streaks[i] <= k:
                k -= loss_streaks[i]
                score += loss_streaks[i]*2 + 1
                loss_streaks[i] = 0
        left = sum(loss_streaks)
        score += 2*min(left, k)
        k -= min(left, k)

        if k and last:
            score += 2*min(last, k)
            k -= min(last, k)
        if k and first:
            score += 2*min(first, k) - 1
            mn = min(first, k)
            k -= mn
            first -= mn
            if first == 0:
                score += 1
        return score

    print(way1())


# wow, I'm bad

t = int(input())

for _ in range(t):
    n,K = map(int,input().split())
    s = input()
    n = len(s)

    def way1():
        global n,K,s

        if s.find('W') == -1:
            return max(0, 2*min(K, n) - 1)

        k = K
        score = int(s[0] == 'W')
        for i in range(1, n):
            if s[i-1] == s[i] == 'W':
                score += 2
            elif s[i] == 'W':
                score += 1

        loss_streaks = [len(x) for x in s.split('W') if x != '']
        if s[0] == 'L':
            first = loss_streaks[0]
            del loss_streaks[0]
        else:
            first = 0
        if s[-1] == 'L' and loss_streaks:
            last = loss_streaks[-1]
            del loss_streaks[-1]
        else:
            last = 0

        loss_streaks.sort()
        for i in range(len(loss_streaks)):
            if loss_streaks[i] <= k:
                k -= loss_streaks[i]
                score += loss_streaks[i]*2 + 1
                loss_streaks[i] = 0
        left = sum(loss_streaks)
        score += 2*min(left, k)
        k -= min(left, k)

        if k and last:
            score += 2*min(last, k)
            k -= min(last, k)
        if k and first:
            score += 2*min(first, k)
        return score

    print(way1())


# wow, I'm bad

t = int(input())

for _ in range(t):
    n,K = map(int,input().split())
    s = input()

    def way1():
        global n,K,s
        k = K
        score = int(s[0] == 'W')
        for i in range(1, n):
            if s[i-1] == s[i] == 'W':
                score += 2
            elif s[i] == 'W':
                score += 1

        loss_streaks = [len(x) for x in s.split('W') if x != '']
        if s[0] == 'L':
            first = loss_streaks[0]
            del loss_streaks[0]
        else:
            first = 0
        if s[-1] == 'L' and loss_streaks:
            last = loss_streaks[-1]
            del loss_streaks[0-1]
        else:
            last = 0

        loss_streaks.sort()
        for i in range(len(loss_streaks)):
            if loss_streaks[i] <= k:
                k -= loss_streaks[i]
                score += loss_streaks[i]*2 + 1
                loss_streaks[i] = 0
        left = sum(loss_streaks)
        score += 2*min(left, k)
        k -= min(left, k)
        if k and last:
            score += 2*min(last, k)
            k -= min(last, k)
        if k and first:
            score += 2*min(first, k) - 1
            k -= min(first, k)

        return score

    def way2():
        if s.count('L') <= K:
            return len(s)*2 - 1
        else:
            return 0

    print(max(way1(), way2()))


for inx in range(int(input())):
    n,k = map(int,input().split());l = input();b=sc=0;g=[];p='L'
    for c in l:
        if c=='W':
            sc = (sc + 2 if p=='W' else sc + 1);p='W'
            if b:g.append(b)
            b=0
        else:p='L';b+=1
    if b:g.append(b)
    cbg=cen=0
    if l[0]=='L':cbg=g.pop(0)
    if l[-1]=='L':
        if sc:cen=g.pop()
    g.sort()
    while k and g:
        b=g.pop(0)
        if k>=b:k-=b;sc+=2*b+1
        else:sc+=2*k;k=0
    if k:sc = (sc + 2*min(k,cbg+cen) if sc else sc + 2*min(k,cbg)-1)
    print(sc)


I=input
for _ in[0]*int(I()):
 n,k=map(int,I().split());s=I();c=s.count('W');n=min(n,c+k);a=sorted(map(len,filter(None,s.strip('L').split('W'))))
 while a and c+a[0]<=n:c+=a.pop(0)
 print((2*n-len(a)or 1)-1)


for _ in range(int(input())):
    n,k=map(int, input().split())
    s=input()
    w=s.count('W')
    if s.count('L')<=k:
        ans=2*n-1
        print(ans)
    elif k==0 and w==0:
        print(0)

    else:
        i=0

        c1=s.find('W')
        c2=s.rfind('W')
        if c1==-1:
            ans=2*k-1
        else:
            l=[]
            s=s[c1+1:c2]
            #print(s)
            i=0
            c=0
            while i<len(s):

                if s[i]=='L':
                    c=1
                    j=i+1
                    while j<len(s) and s[j]=='L':
                        c+=1
                        j+=1
                    l.append(c)
                    i=j
                else:
                    i+=1
            l.sort()
            #print(l)
            i=0
            streak=len(l)+1
            #print(streak)
            k0=k
            while i<len(l) and k>0:
                if l[i]<=k:
                    k-=l[i]
                    streak-=1
                i+=1
            #print(streak)
            if streak==0:
                ans=2*(w+k0)-1
            else:
                ans=2*(w+k0)-streak
        #print(w,k)
        print(ans)


import math
T=int(input())
for _ in range(T):
    n,k=map(int,input().split())
    s=list(input())
    edge=0
    ans=0
    f=0
    for i in s:
        if i=='W':
            f=1
            break
    if s[0]=='W':
        ans=1
    for i in range(1,n):
        if s[i-1]=='W' and s[i]=='W':
            ans+=2
        elif s[i]=='W':
            ans+=1
    for i in range(n):
        if s[i]=='W':
            break
        edge+=1
    for j in range(n-1,-1,-1):
        if s[j]=='W':
            break
        else:
            edge+=1
    st,en=i,j
    l=[]
    c=0
    for i in range(st,en+1):
        if s[i]=='L':
            c+=1
        else:
            if c:
                l.append(c)
            c=0
    l.sort()
    for i in l:
        if i<=k:
            ans+=(2*i+1)
            k-=i
        else:
            edge+=i
    able=min(edge,k)
    if f:
        ans+=(2*able)
    else:
        ans+=(2*able-1)
    print(max(ans,0))


import itertools

def remove_beginning(lst, bad):
    idx = 0
    while lst[idx] == bad:
        idx += 1
        if len(lst) == idx:
            break
    return idx

def solve():
    n, k = [int(x) for x in input().strip().split()]
    game_scores = list(input().strip())
    win, lose = 'W', 'L'

    first_good_pos = remove_beginning(game_scores, lose)
    first_range = first_good_pos
    game_scores = game_scores[first_good_pos:]
    # print(f'Games after removing from head {game_scores}')
    game_scores.reverse()
    if not game_scores:
        return max(2 * min(k, first_range) - 1, 0)
    last_good_pos = remove_beginning(game_scores, lose)
    last_range = last_good_pos
    game_scores = game_scores[last_good_pos:]
    game_scores.reverse()
    # print(f'Games after removing from tail {game_scores}, {last_range}')

    assignable_points_from_list_ends = first_range + last_range

    lose_lengths = []
    for key, group in itertools.groupby(game_scores):
        lose_lengths.append([key, len(list(group))])
    # print(lose_lengths)
    initial_points = sum(map(lambda t: 0 if t[0] == lose else 2 * t[1] - 1, lose_lengths))
    # print(f'Initial points {initial_points}. Assignable points from bounds {assignable_points_from_list_ends}')
    lose_lengths = list(filter(lambda t: t > 0, map(lambda t: 0 if t[0] == win else t[1], lose_lengths)))
    if n == 1:
        return max(1, initial_points + (k == 1))
    # print(lose_lengths)
    lose_lengths.sort()
    for l in lose_lengths:
        if k >= l:
            k, initial_points = k - l, initial_points + 2 * (l - 1) + 3
        else:
            k, initial_points = 0, initial_points + 2 * k

    initial_points += 2 * min (k, assignable_points_from_list_ends)
    return initial_points

if __name__=='__main__':
    for _ in range(int(input().strip())):
        print(solve())


import itertools

def remove_beginning(lst, bad):
    idx = 0
    while lst[idx] == bad:
        idx += 1
        if len(lst) == idx:
            break
    return idx

def solve():
    n, k = [int(x) for x in input().strip().split()]
    game_scores = list(input().strip())
    win, lose = 'W', 'L'

    first_good_pos = remove_beginning(game_scores, lose)
    first_range = first_good_pos
    game_scores = game_scores[first_good_pos:]
    # print(f'Games after removing from head {game_scores}')
    game_scores.reverse()
    if not game_scores:
        return max(2 * min(k, first_range) - 1, 0)
    last_good_pos = remove_beginning(game_scores, lose)
    last_range = last_good_pos
    game_scores = game_scores[last_good_pos:]
    game_scores.reverse()
    # print(f'Games after removing from tail {game_scores}, {last_range}')

    assignable_points_from_list_ends = first_range + last_range

    lose_lengths = []
    for key, group in itertools.groupby(game_scores):
        lose_lengths.append([key, len(list(group))])
    # print(lose_lengths)
    initial_points = sum(map(lambda t: 0 if t[0] == lose else 2 * t[1] - 1, lose_lengths))
    # print(f'Initial points {initial_points}. Assignable points from bounds {assignable_points_from_list_ends}')
    lose_lengths = list(filter(lambda t: t > 0, map(lambda t: 0 if t[0] == win else t[1], lose_lengths)))
    if n == 1:
        if game_scores[0] == win:
            return 1
        return 1 if (k == 1) else 0
    # print(lose_lengths)
    lose_lengths.sort()
    for l in lose_lengths:
        if k >= l:
            k, initial_points = k - l, initial_points + 2 * (l - 1) + 3
        else:
            k, initial_points = 0, initial_points + 2 * k

    initial_points += 2 * min (k, assignable_points_from_list_ends)
    return initial_points

if __name__=='__main__':
    for _ in range(int(input().strip())):
        print(solve())


#include <bits/stdc++.h>
using namespace std;

int n,x;
int li,ri,ci,d;
int ans=INT_MAX;
vector< pair <int, pair<int,int> > > v;
pair<int,int> lr;
pair< int,pair <int,int> >pp;
vector<int> dur[200009];

int fin(int i){
    int ans=0,fl=(v[i].second).first,fr=(v[i].second).second,sl,sr;
    int newday=x-(fr-fl+1);
    int newsi=dur[newday].size();
    for(int j=0;j<newsi;j++){
        int newvo=dur[newday][j];
        sl=(v[newvo].second).first;
        sr=(v[newvo].second).second;
        if(sl>fr||sr<fl){
            return v[newvo].first;
        }
    }
    return INT_MAX;
}

int main(){
    scanf("%d %d",&n,&x);
    for(int i=0;i<n;i++){
        scanf("%d %d %d",&li,&ri,&ci);
        d=ri-li+1;
        if(d>=x) continue;
        else{
            lr.first=li;lr.second=ri;
            pp.first=ci;
            pp.second=lr;
            v.push_back(pp);
        }
    }
    int si=v.size();
    sort(v.begin(),v.end());
    for(int i=0;i<si;i++){
        d=(v[i].second).second-(v[i].second).first+1;
        dur[d].push_back(i);
    }
    for(int i=0;i<si;i++){
        int cost=v[i].first;
        if(cost>=ans) break;
        int ans2=fin(i);
        if(ans2!=INT_MAX) ans=min(ans,ans2+cost);
    }
    if(ans!=INT_MAX) printf("%d",ans);
    else printf("-1");
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int n,x,d;
int li[200009],ri[200009],ci[200009],dd[200009];
int ans=INT_MAX;
int dursi[200009];
int durmin[200009],durmax[200009];
vector< pair <int, pair<int,int> > > v;
vector<int> dur[200009];
map<pair<int,int>,int >m;
map<pair<int,int>,int >mlabel;

int fin(int i,int cost){
    int fl=(v[i].second).first,fr=(v[i].second).second,sl,sr;
    int newday=x-(fr-fl+1);
    if((durmin[newday]+newday-1>=fl)&&(durmax[newday]-newday+1<=fr)) return INT_MAX;
    int newsi=dursi[newday];
    for(int j=0;j<newsi;j++){
        int newvo=dur[newday][j];
        sl=(v[newvo].second).first;
        sr=(v[newvo].second).second;
        if(sl>fr||sr<fl){
            return v[newvo].first;
        }
        if (v[newvo].first+cost>=ans) return INT_MAX;
    }
    return INT_MAX;
}

int main(){
    scanf("%d %d",&n,&x);
    for(int i=0;i<n;i++){
        scanf("%d %d %d",&li[i],&ri[i],&ci[i]);
        dd[i]=ri[i]-li[i]+1;
        int t=m[make_pair(li[i],ri[i])];
        if(t>0&&ci[i]<t){
            m[make_pair(li[i],ri[i])]=t;
            mlabel[make_pair(li[i],ri[i])]=i;
        }
        else{
            m[make_pair(li[i],ri[i])]=ci[i];
            mlabel[make_pair(li[i],ri[i])]=i;
        }
        if(dd[i]>=x) continue;
        else dursi[dd[i]]++;
    }
    for(int i=1;i<=x;i++){
        durmin[i]=INT_MAX;
        durmax[i]=INT_MIN;
    }
    for(int i=0;i<n;i++){
        if(dursi[x-dd[i]]){
            if(mlabel[make_pair(li[i],ri[i])]==i){
                v.push_back(make_pair(ci[i],make_pair(li[i],ri[i])));
                durmin[dd[i]]=min(durmin[dd[i]],li[i]);
                durmax[dd[i]]=max(durmax[dd[i]],ri[i]);
            }
            else dursi[dd[i]]--;
        }
    }
    int si=v.size();
    sort(v.begin(),v.end());
    for(int i=0;i<si;i++){
        d=(v[i].second).second-(v[i].second).first+1;
        dur[d].push_back(i);
    }
    for(int i=0;i<si;i++){
        int cost=v[i].first;
        if(cost>=ans) break;
        int ans2=fin(i,cost);
        if(ans2!=INT_MAX) ans=min(ans,ans2+cost);
    }
    if(ans!=INT_MAX) printf("%d",ans);
    else printf("-1");
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int n,x,l,r,c,d;
int li[200009],ri[200009],ci[200009],cost[200009];
vector< pair< pair<int,int> ,int> > v;
set<pair< int,pair<int,int> > > s; //last dur cost
int ans=INT_MAX;

int main(){
    scanf("%d%d",&n,&x);
    for(int i=0;i<n;i++){
        scanf("%d%d%d",&li[i],&ri[i],&ci[i]);
        d=ri[i]-li[i]+1;
        if(d<x){
            v.push_back(make_pair(make_pair(li[i],ri[i]),ci[i]));
        }
    }
    sort(v.begin(),v.end());
    n=v.size();
    for(int i=1;i<=x;i++)   cost[i]=INT_MAX;
    for(int i=0;i<n;i++){
        l=(v[i].first).first;
        r=(v[i].first).second;
        d=r-l+1;
        c=(v[i].second);
        s.insert(make_pair(r,make_pair(d,c)));
        while( (!s.empty()) && ( (s.begin()->first)<l) ){
            d=(s.begin()->second).first;
            cost[d]=min(cost[d],(s.begin()->second).second);
            s.erase(s.begin());
        }
        if(cost[x-d]!=INT_MAX){
            ans=min(ans,c+cost[x-d]);
        }
    }
    if(ans!=INT_MAX)    printf("%d",ans);
    else printf("-1");
}


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
using namespace std;

struct node
{
	int l,r,co,len;
}h[maxn];
vector<int> v[maxn];
int cc=0;
void add(int l,int r,int co,int len)
{
	cc++;
	v[len].push_back(cc);
	h[cc].l=l;
	h[cc].r=r;
	h[cc].co=co;
	h[cc].len=len;
}
int main()
{
    int n,x;  cin>>n>>x;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
    	cin>>a>>b>>c;
    	add(a,b,c,b-a+1);
	}
	int ans=inf,ff=0;
	for(int i=1;i<x;i++)
	{
		 if(v[i].size()==0) continue;
		 int t=x-i;
		 if(v[t].size()==0) continue;
		 for(int j=0;j<v[i].size();j++)
		 {
		 	 int t1=v[i][j];
		 	 for(int k=0;k<v[t].size();k++)
		 	 {
		 	 	 int t2=v[t][k];
		 	 	 if(h[t1].l>h[t2].r||h[t1].r<h[t2].l)
		 	 	 {
		 	 	 	ans=min(ans,h[t1].co+h[t2].co);
		 	 	 	ff=1;
				 }
			 }
		 }
	}
	if(ff) cout<<ans<<endl;
	else cout<<"-1"<<endl;
return 0;
}


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
const int maxn=1e6+10;
const int inf=2*0x3f3f3f3f;
using namespace std;

struct node
{
	int l,r,co,v,st;
}h[maxn];
int cc=0;
void add(int l,int r,int co,int len,int st)
{
	cc++;
	h[cc].l=l;
	h[cc].r=r;
	h[cc].co=co;
	h[cc].v=len;
	h[cc].st=st;
}
int cmp(node a,node b)
{
	if(a.l==b.l) return a.st>b.st;
	return a.l<b.l;
}
int sum[maxn];
int main()
{
    int n,x;  cin>>n>>x;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
    	cin>>a>>b>>c;
    	add(a,b,c,b-a+1,1);
    	add(b,a,c,b-a+1,-1);
	}
	sort(h+1,h+1+cc,cmp);
	int ans=inf,ff=0;
	memset(sum,-1,sizeof(sum));
	for(int i=1;i<=cc;i++)
	{
	    if(h[i].st==1)
	    {
	    	if(h[i].v<x&&sum[x-h[i].v]!=-1) ans=min(ans,h[i].co+sum[x-h[i].v]);
		}
		else
		{
			if(h[i].v<x&&(sum[h[i].v]==-1||sum[h[i].v]>h[i].co))  sum[h[i].v]=h[i].co;
		}
	}
	if(ans==inf) ans=-1;
	cout<<ans<<endl;
return 0;
}


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
using namespace std;

struct node
{
	int l,r,co,v,st;
}h[maxn];
int cc=0;
void add(int l,int r,int co,int len,int st)
{
	cc++;
	h[cc].l=l;
	h[cc].r=r;
	h[cc].co=co;
	h[cc].v=len;
	h[cc].st=st;
}
int cmp(node a,node b)
{
	if(a.l==b.l) return a.r>b.r;
	return a.l<b.l;
}
int sum[maxn];
int main()
{
    int n,x;  cin>>n>>x;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
    	cin>>a>>b>>c;
    	add(a,b,c,b-a+1,1);
    	add(b,a,c,b-a+1,-1);
	}
	sort(h+1,h+1+cc,cmp);
	int ans=inf,ff=0;
	memset(sum,-1,sizeof(sum));
	for(int i=1;i<=cc;i++)
	{
	    if(h[i].st==1)
	    {
	    	if(h[i].v<x&&sum[x-h[i].v]!=-1) ans=min(ans,h[i].co+sum[x-h[i].v]);
		}
		else
		{
			if(h[i].v<x&&(sum[h[i].v]==-1||sum[h[i].v]>h[i].co))  sum[h[i].v]=h[i].co;
		}
	}
	if(ans==inf) ans=-1;
	cout<<ans<<endl;
return 0;
}


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
using namespace std;

struct node
{
	int l,r,co,v,st;
}h[maxn];
int cc=0;
void add(int l,int r,int co,int len,int st)
{
	cc++;
	h[cc].l=l;
	h[cc].r=r;
	h[cc].co=co;
	h[cc].v=len;
	h[cc].st=st;
}
int cmp(node a,node b)
{
	if(a.l==b.l) return a.st>b.st;
	return a.l<b.l;
}
int sum[maxn];
int main()
{
    int n,x;  cin>>n>>x;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
    	cin>>a>>b>>c;
    	add(a,b,c,b-a+1,1);
    	add(b,a,c,b-a+1,-1);
	}
	sort(h+1,h+1+cc,cmp);
	int ans=inf,ff=0;
	memset(sum,-1,sizeof(sum));
	for(int i=1;i<=cc;i++)
	{
	    if(h[i].st==1)
	    {
	    	if(h[i].v<x&&sum[x-h[i].v]!=-1) ans=min(ans,h[i].co+sum[x-h[i].v]);
		}
		else
		{
			if(h[i].v<x&&(sum[h[i].v]==-1||sum[h[i].v]>h[i].co))  sum[h[i].v]=h[i].co;
		}
	}
	if(ans==inf) ans=-1;
	cout<<ans<<endl;
return 0;
}


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
using namespace std;

struct node
{
	int l,r,co,v,st;
}h[maxn];
int cc=0;
void add(int l,int r,int co,int len,int st)
{
	cc++;
	h[cc].l=l;
	h[cc].r=r;
	h[cc].co=co;
	h[cc].v=len;
	h[cc].st=st;
}
int cmp(node a,node b)
{
	if(a.l==b.l) return a.r>b.r;
	return a.l<b.l;
}
int sum[maxn];
int main()
{
    int n,x;  cin>>n>>x;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
    	cin>>a>>b>>c;
    	add(a,b,c,b-a+1,1);
    	add(b,a,c,b-a+1,-1);
	}
	sort(h+1,h+1+n,cmp);
	int ans=inf,ff=0;
	memset(sum,-1,sizeof(sum));
	for(int i=1;i<=cc;i++)
	{
	    if(h[i].st==1)
	    {
	    	if(h[i].v<x&&sum[x-h[i].v]!=-1) ans=min(ans,h[i].co+sum[x-h[i].v]);
		}
		else
		{
			if(h[i].v<x&&(sum[h[i].v]==-1||sum[h[i].v]>h[i].co))  sum[h[i].v]=h[i].co;
		}
	}
	if(ans==inf) ans=-1;
	cout<<ans<<endl;
return 0;
}


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define ll long long
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
using namespace std;

struct node
{
	int l,r,co,len;
}h[maxn];
vector<int> v[maxn];
int cc=0;
void add(int l,int r,int co,int len)
{
	cc++;
	v[len].push_back(cc);
	h[cc].l=l;
	h[cc].r=r;
	h[cc].co=co;
	h[cc].len=len;
}
int main()
{
    int n,x;  cin>>n>>x;
    int a,b,c;
    for(int i=1;i<=n;i++)
    {
    	cin>>a>>b>>c;
    	add(a,b,c,b-a+1);
	}
	int ans=inf,ff=0;
	for(int i=1;i<x;i++)
	{
		int a=v[i].size();
		 if(a==0) continue;
		 int t=x-i;
		 int b=v[t].size();
		 if(b==0) continue;
		 for(int j=0;j<a;j++)
		 {
		 	 int t1=v[i][j];
		 	 for(int k=0;k<b;k++)
		 	 {
		 	 	 int t2=v[t][k];
		 	 	 if(h[t1].l>h[t2].r||h[t1].r<h[t2].l)
		 	 	 {
		 	 	 	ans=min(ans,h[t1].co+h[t2].co);
		 	 	 	ff=1;
				 }
			 }
		 }
	}
	if(ff) cout<<ans<<endl;
	else cout<<"-1"<<endl;
return 0;
}


#include<bits/stdc++.h>
using namespace std;
long long mini(long long a, long long b)
{
    if(a<=b)return a;
    return b;
}
long long cost[200005];
long long a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    long long ma = 2000000007;
    long long ans = ma;
    scanf("%d%d",&n,&x);
    for(i=0;i<=200000;i++)cost[i] = ma+1;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(-1,i));
        v[r].push_back(make_pair(1,i));
    }
    for(i=1;i<=200000;i++)
    {
        int l = v[i].size();
        int j;
        sort(v[i].begin(),v[i].end());
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==-1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0 && req < 200000)
                {
                    // find value for this length
                    long long cur = cost[req];
                   ans = mini(ans, cur + a[ind]);
                }
            }
            else {
                cost[len] = mini(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
long long mini(long long a, long long b)
{
    if(a<=b)return a;
    return b;
}
long long cost[200005];
long long a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    long long ma = 2000000007;
    long long ans = ma;
    scanf("%d%d",&n,&x);
    for(i=1;i<=x;i++)cost[i] = ma;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(1,i));
        v[r].push_back(make_pair(-1,i));
    }
    for(i=1;i<=200000;i++)
    {
        int l = v[i].size();
        int j;
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0)
                {
                    // find value for this length
                    long long cur = cost[req];
                    if(cur<ans)
                    {
                        cur += a[ind];
                        if(cur < ans)
                        {
                            ans = cur;
                        }
                    }
                }
            }
            else {
                cost[len] = mini(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int cost[200005];
int a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    int ma = 2000000007;
    long long ans = ma;
    scanf("%d%d",&n,&x);
    for(i=1;i<=x;i++)cost[i] = ma;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(1,i));
        v[r].push_back(make_pair(-1,i));
    }
    for(i=1;i<=200000;i++)
    {
        int l = v[i].size();
        int j;
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0)
                {
                    // find value for this length
                    long long cur = cost[req];
                    if(cur<ans)
                    {
                        cur += a[ind];
                        if(cur < ans)
                        {
                            ans = cur;
                        }
                    }
                }
            }
            else {
                cost[len] = min(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int cost[200005];
int a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    int ma = 2000000007;
    int ans = ma;
    scanf("%d%d",&n,&x);
    for(i=1;i<=x;i++)cost[i] = ma;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(1,i));
        v[r].push_back(make_pair(-1,i));
    }
    for(i=1;i<=200000;i++)
    {
        int l = v[i].size();
        int j;
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0)
                {
                    // find value for this length
                    int cur = cost[req];
                    if(cur<ans)
                    {
                        cur += a[ind];
                        if(cur < ans)
                        {
                            ans = cur;
                        }
                    }
                }
            }
            else {
                cost[len] = min(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int cost[200005];
int a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    int ma = 2000000007;
    int ans = ma;
    scanf("%d%d",&n,&x);
    for(i=1;i<=x;i++)cost[i] = ma;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(1,i));
        v[r+1].push_back(make_pair(-1,i));
    }
    for(i=1;i<=200001;i++)
    {
        int l = v[i].size();
        int j;
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0)
                {
                    // find value for this length
                    int cur = cost[req];
                    if(cur<ans)
                    {
                        cur += a[ind];
                        if(cur < ans)
                        {
                            ans = cur;
                        }
                    }
                }
            }
            else {
                cost[len] = min(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
long long mini(long long a, long long b)
{
    if(a<=b)return a;
    return b;
}
long long cost[200005];
long long a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    long long ma = 2000000007;
    long long ans = ma;
    scanf("%d%d",&n,&x);
    for(i=0;i<=200000;i++)cost[i] = ma+1;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(1,i));
        v[r].push_back(make_pair(-1,i));
    }
    for(i=1;i<=200000;i++)
    {
        int l = v[i].size();
        int j;
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0 && req < 200000)
                {
                    // find value for this length
                    long long cur = cost[req];
                   ans = mini(ans, cur + a[ind]);
                }
            }
            else {
                cost[len] = mini(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int cost[200005];
int a[200005];
vector< pair<int,int> > v[200005];
int st[200005],en[200005];
int main() {
    int n,x,i;
    int ma = 2000000007;
    int ans = ma;
    scanf("%d%d",&n,&x);
    for(i=1;i<=x;i++)cost[i] = ma;
    for(i=1;i<=n;i++)
    {
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        a[i] = c;
        // -1 means start of segment, 1 for end
        st[i] = l;
        en[i] = r;
        v[l].push_back(make_pair(1,i));
        v[r+1].push_back(make_pair(-1,i));
    }
    for(i=1;i<=200000;i++)
    {
        int l = v[i].size();
        int j;
        // at this point check starting segment calculate answer, for ending update cost
        for(j=0;j<l;j++)
        {
            int ind = v[i][j].second;
            int len = en[ind] - st[ind] + 1;
            if(v[i][j].first==1)
            {
                // starting so calculate answer

                int req = x - len;
                if(req>0)
                {
                    // find value for this length
                    int cur = cost[req];
                    if(cur<ans)
                    {
                        cur += a[ind];
                        if(cur < ans)
                        {
                            ans = cur;
                        }
                    }
                }
            }
            else {
                cost[len] = min(cost[len],a[ind]);
            }
        }
    }
    if(ans>=ma)ans = -1;
    printf("%d\n",ans);
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

long long n , x ;

struct node {
    long long l , r , c ;
    long long len ;
    node () {}
    node (long long _len , long long _c) {len = _len ; c = _c ; }
};

long long cost[200050] ;

vector<node > a[200050] , b[200050] ;

int main () {
    cin >> n >> x ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        long long l , r , c ;
        cin >> l >> r >> c ;
        a[l].pb(node{r-l+1,c}) ;
        b[r].pb(node{r-l+1,c}) ;
    }
    long long ans = -1 ;

    for(long long i = 0 ; i <= 200000 ; i ++ ) cost[i] = 999999999999 ;

    for(long long i = 1 ; i <= 200000 ; i ++ ) {
         for(long long j = 0 ; j < a[i].size() ; j ++ ) {
            long long cos = a[i][j].c ;
            long long len = a[i][j].len ;
            if(ans == -1 || ans > cos + cost[x - len]) {
                ans = cos + cost[x - len] ;
            }
         }
         for(long long j = 0 ; j < b[i].size() ; j ++ ) {
            long long cos = b[i][j].c ;
            long long len = b[i][j].len ;
            cost[len] = min(cost[len] , cos) ;
         }
    }
    if(ans > 999999999999) ans = -1 ;
    printf("%lld\n" , ans) ;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

long long n , x ;

struct node {
    long long c ;
    long long l , r ;
    long long len ;
}a[200050];

bool cmp(node a , node b) {
    return a.len < b.len ;
}

struct tre{
    long long l , r ;
    long long minn ;
    long long really ;
}t[200050 * 5];

void build(long long ro , long long l , long long r) {
    t[ro].l = l ; t[ro].r = r ;
    t[ro].really = 0 ;
    t[ro].minn = 999999999999999 ;
    if(l == r) return ;
    long long mid = (l + r) / 2 ;
    build(ro * 2 , l , mid) ;
    build(ro * 2 + 1 , mid + 1 , r) ;
}

long long query1(long long ro , long long pos , long long rea) {
    if(t[ro].l == t[ro].r) {
        if(t[ro].really != rea) {
            return 999999999999999 ;
        }
        else return t[ro].minn ;
    }
    long long mid = (t[ro].r + t[ro].l) / 2 ;
    if(pos <= mid) return query1(ro*2 , pos , rea) ;
    else return query1(ro*2+1 , pos , rea) ;
}
long long query2(long long ro , long long l , long long r , long long rea) {
    if(r < l) return 999999999999999 ;
    if(t[ro].l >= l && t[ro].r <= r) {
        if(t[ro].really != rea) return 999999999999999 ;
        else return t[ro].minn ;
    }
    long long mid = (t[ro].l + t[ro].r) / 2 ;
    if(r <= mid) return query2(ro*2 , l , r , rea) ;
    else if(l >= mid+1) return query2(ro*2+1, l , r , rea) ;
    else {
        return min(query2(ro*2 , l , r , rea) , query2(ro*2+1 , l , r , rea)) ;
    }

}
void upda(long long ro , long long pos , long long val , long long rea) {
    if(t[ro].l == t[ro].r) {
        t[ro].really = rea ;
        t[ro].minn = val ;
        return ;
    }
    long long mid = (t[ro].l + t[ro].r) / 2 ;
    if(pos <= mid) upda(ro*2 , pos , val , rea) ;
    else upda(ro*2+1 , pos , val , rea) ;
    if(t[ro].really != rea) {
        t[ro].minn = val ;
    }
    else {
        t[ro].minn = min(t[ro].minn , val) ;
    }
    t[ro].really = rea ;
}

int main () {
    cin >> n >> x ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        cin >> a[i].l >> a[i].r >> a[i].c ;
        a[i].len = a[i].r - a[i].l + 1 ;
        if((x - a[i].len) < a[i].len) {
            a[i].len = (x - a[i].len) ;
        }
    }
    build(1 , 1 , 200000) ;
    long long ans = -1 ;
    sort(a+1 , a+1+n , cmp) ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        long long j ;
        for(j = i ; j <= n ; j ++ ) {
            if(a[i].len == a[j].len) continue ;
            else break ;
        }
        j -- ;
        for(long long k = i ; k <= j ; k ++ ) {
            if(a[k].len == (a[k].r - a[k].l + 1)) {
                long long minn = query1(1 , a[k].r , i) ;
                if(minn > a[k].c) upda(1 , a[k].r , a[k].c , i) ;
            }
        }
        for(long long k = i ; k <= j ; k ++ ) {
            if(a[k].len == (x - (a[k].r - a[k].l + 1))) {
                long long minn = min(query2(1 , 1 , a[k].l - 1 , i) , query2(1 , a[k].r + (x - a[k].len) , 200000 , i)) ;
                if(minn == 999999999999999) continue ;
                if(ans == -1 || ans > minn + a[k].c) {
                    ans = a[k].c + minn ;
                }
            }
        }
        i = j ;
    }
    printf("%lld\n" , ans) ;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

long long n , x ;

struct node {
    long long c ;
    long long l , r ;
    long long len ;
}a[200050];

bool cmp(node a , node b) {
    return a.len < b.len ;
}

struct tre{
    long long l , r ;
    long long minn ;
    long long really ;
}t[200050 * 5];

void build(long long ro , long long l , long long r) {
    t[ro].l = l ; t[ro].r = r ;
    t[ro].really = 0 ;
    t[ro].minn = 999999999999999 ;
    if(l == r) return ;
    long long mid = (l + r) / 2 ;
    build(ro * 2 , l , mid) ;
    build(ro * 2 + 1 , mid + 1 , r) ;
}

long long query1(long long ro , long long pos , long long rea) {
    if(t[ro].l == t[ro].r) {
        if(t[ro].really != rea) {
            return 999999999999999 ;
        }
        else return t[ro].minn ;
    }
    long long mid = (t[ro].r + t[ro].l) / 2 ;
    if(pos <= mid) return query1(ro*2 , pos , rea) ;
    else return query1(ro*2+1 , pos , rea) ;
}
long long query2(long long ro , long long l , long long r , long long rea) {
    if(r < l) return 999999999999999 ;
    if(t[ro].l >= l && t[ro].r <= r) {
        if(t[ro].really != rea) return 999999999999999 ;
        else return t[ro].minn ;
    }
    long long mid = (t[ro].l + t[ro].r) / 2 ;
    if(r <= mid) return query2(ro*2 , l , r , rea) ;
    else if(l >= mid+1) return query2(ro*2+1, l , r , rea) ;
    else {
        return min(query2(ro*2 , l , r , rea) , query2(ro*2+1 , l , r , rea)) ;
    }

}
void upda(long long ro , long long pos , long long val , long long rea) {
    if(t[ro].l == t[ro].r) {
        t[ro].really = rea ;
        t[ro].minn = val ;
        return ;
    }
    long long mid = (t[ro].l + t[ro].r) / 2 ;
    if(pos <= mid) upda(ro*2 , pos , val , rea) ;
    else upda(ro*2+1 , pos , val , rea) ;
    if(t[ro].really != rea) {
        t[ro].minn = val ;
    }
    else {
        t[ro].minn = min(t[ro].minn , val) ;
    }
}

int main () {
    cin >> n >> x ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        cin >> a[i].l >> a[i].r >> a[i].c ;
        a[i].len = a[i].r - a[i].l + 1 ;
        if((x - a[i].len) < a[i].len) {
            a[i].len = (x - a[i].len) ;
        }
    }
    build(1 , 1 , 200000) ;
    long long ans = -1 ;
    sort(a+1 , a+1+n , cmp) ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        long long j ;
        for(j = i ; j <= n ; j ++ ) {
            if(a[i].len == a[j].len) continue ;
            else break ;
        }
        j -- ;
        for(long long k = i ; k <= j ; k ++ ) {
            if(a[k].len == (a[k].r - a[k].l + 1)) {
                long long minn = query1(1 , a[k].r , i) ;
                if(minn > a[k].c) upda(1 , a[k].r , a[k].c , i) ;
            }
        }
        for(long long k = i ; k <= j ; k ++ ) {
            if(a[k].len == (x - (a[k].r - a[k].l + 1))) {
                long long minn = min(query2(1 , 1 , a[k].l - 1 , i) , query2(1 , a[k].r + (x - a[k].len) , 200000 , i)) ;
                if(minn == 999999999999999) continue ;
                if(ans == -1 || ans > minn + a[k].c) {
                    ans = a[k].c + minn ;
                }
            }
        }
        i = j ;
    }
    printf("%lld\n" , ans) ;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

long long n , x ;

struct node {
    long long l , r , c ;
    long long len ;
    node () {}
    node (long long _len , long long _c) {len = _len ; c = _c ; }
};

long long cost[200050] ;

vector<node > a[200050] , b[200050] ;

int main () {
    cin >> n >> x ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        long long l , r , c ;
        cin >> l >> r >> c ;
        a[l].pb({r-l+1,c}) ;
        b[r].pb({r-l+1,c}) ;
    }
    long long ans = -1 ;

    for(long long i = 0 ; i <= 200000 ; i ++ ) cost[i] = 999999999999 ;

    for(long long i = 1 ; i <= 200000 ; i ++ ) {
         for(long long j = 0 ; j < a[i].size() ; j ++ ) {
            long long cos = a[i][j].c ;
            long long len = a[i][j].len ;
            if(ans == -1 || ans > cos + cost[x - len]) {
                ans = cos + cost[x - len] ;
            }
         }
         for(long long j = 0 ; j < b[i].size() ; j ++ ) {
            long long cos = b[i][j].c ;
            long long len = b[i][j].len ;
            cost[len] = min(cost[len] , cos) ;
         }
    }
    if(ans > 999999999999) ans = -1 ;
    printf("%lld\n" , ans) ;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

int n , x ;

struct node {
    int c ;
    int l , r ;
    int len ;
}a[200050];

bool cmp(node a , node b) {
    return a.len < b.len ;
}

struct tre{
    int l , r ;
    int minn ;
    int really ;
}t[200050 * 5];

void build(int ro , int l , int r) {
    t[ro].l = l ; t[ro].r = r ;
    t[ro].really = 0 ;
    t[ro].minn = 999999999 ;
    if(l == r) return ;
    int mid = (l + r) / 2 ;
    build(ro * 2 , l , mid) ;
    build(ro * 2 + 1 , mid + 1 , r) ;
}

int query1(int ro , int pos , int rea) {
    if(t[ro].l == t[ro].r) {
        if(t[ro].really != rea) {
            return 999999999 ;
        }
        else return t[ro].minn ;
    }
    int mid = (t[ro].r + t[ro].l) / 2 ;
    if(pos <= mid) return query1(ro*2 , pos , rea) ;
    else return query1(ro*2+1 , pos , rea) ;
}
int query2(int ro , int l , int r , int rea) {
    if(r < l) return 999999999 ;
    if(t[ro].l >= l && t[ro].r <= r) {
        if(t[ro].really != rea) return 999999999 ;
        else return t[ro].minn ;
    }
    int mid = (t[ro].l + t[ro].r) / 2 ;
    if(r <= mid) return query2(ro*2 , l , r , rea) ;
    else if(l >= mid+1) return query2(ro*2+1, l , r , rea) ;
    else {
        return min(query2(ro*2 , l , r , rea) , query2(ro*2+1 , l , r , rea)) ;
    }

}
void upda(int ro , int pos , int val , int rea) {
    if(t[ro].l == t[ro].r) {
        t[ro].really = rea ;
        t[ro].minn = val ;
        return ;
    }
    int mid = (t[ro].l + t[ro].r) / 2 ;
    if(pos <= mid) upda(ro*2 , pos , val , rea) ;
    else upda(ro*2+1 , pos , val , rea) ;
    if(t[ro].really != rea) {
        t[ro].minn = val ;
    }
    else {
        t[ro].minn = min(t[ro].minn , val) ;
    }
}

int main () {
    cin >> n >> x ;
    for(int i = 1 ; i <= n ; i ++ ) {
        cin >> a[i].l >> a[i].r >> a[i].c ;
        a[i].len = a[i].r - a[i].l + 1 ;
        if((x - a[i].len) < a[i].len) {
            a[i].len = (x - a[i].len) ;
        }
    }
    build(1 , 1 , 200000) ;
    int ans = -1 ;
    sort(a+1 , a+1+n , cmp) ;
    for(int i = 1 ; i <= n ; i ++ ) {
        int j ;
        for(j = i ; j <= n ; j ++ ) {
            if(a[i].len == a[j].len) continue ;
            else break ;
        }
        j -- ;
        for(int k = i ; k <= j ; k ++ ) {
            if(a[k].len == (a[k].r - a[k].l + 1)) {
                int minn = query1(1 , a[k].r , i) ;
                if(minn > a[k].c) upda(1 , a[k].r , a[k].c , i) ;
            }
        }
        for(int k = i ; k <= j ; k ++ ) {
            if(a[k].len == (x - (a[k].r - a[k].l + 1))) {
                int minn = min(query2(1 , 1 , a[k].l - 1 , i) , query2(1 , a[k].r + (x - a[k].len) , 200000 , i)) ;
                if(minn == 999999999) continue ;
                if(ans == -1 || ans > minn + a[k].c) {
                    ans = a[k].c + minn ;
                }
            }
        }
        i = j ;
    }
    printf("%d\n" , ans) ;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

long long n , x ;

struct node {
    long long l , r , c ;
    long long len ;
    node () {}
    node (long long _len , long long _c) {len = _len ; c = _c ; }
};

long long cost[200050] ;

vector<node > a[200050] , b[200050] ;

int main () {
    cin >> n >> x ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        long long l , r , c ;
        cin >> l >> r >> c ;
        node aa ;
        aa.len = r - l + 1 ;
        aa.c = c ;
        a[l].pb(aa) ;
        b[r].pb(aa) ;
    }
    long long ans = -1 ;

    for(long long i = 0 ; i <= 200000 ; i ++ ) cost[i] = 999999999999 ;

    for(long long i = 1 ; i <= 200000 ; i ++ ) {
         for(long long j = 0 ; j < a[i].size() ; j ++ ) {
            long long cos = a[i][j].c ;
            long long len = a[i][j].len ;
            if(ans == -1 || ans > cos + cost[x - len]) {
                ans = cos + cost[x - len] ;
            }
         }
         for(long long j = 0 ; j < b[i].size() ; j ++ ) {
            long long cos = b[i][j].c ;
            long long len = b[i][j].len ;
            cost[len] = min(cost[len] , cos) ;
         }
    }
    if(ans > 999999999999) ans = -1 ;
    printf("%lld\n" , ans) ;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
#define L long long
#define pb push_back

long long n , x ;

struct node {
    long long l , r , c ;
    long long len ;
    node () {}
    node (long long _len , long long _c) {len = _len ; c = _c ; }
};

long long cost[200050] ;

vector<node > a[200050] , b[200050] ;

int main () {
    cin >> n >> x ;
    for(long long i = 1 ; i <= n ; i ++ ) {
        long long l , r , c ;
        cin >> l >> r >> c ;
        node aa ;
        aa.len = r - l + 1 ;
        aa.c = c ;
        a[l].pb(aa) ;
        b[r].pb(aa) ;
    }
    long long ans = -1 ;

    for(long long i = 0 ; i <= 200000 ; i ++ ) cost[i] = 999999999999 ;

    for(long long i = 1 ; i <= 200000 ; i ++ ) {
         for(long long j = 0 ; j < a[i].size() ; j ++ ) {
            long long cos = a[i][j].c ;
            long long len = a[i][j].len ;
            if(x < len) continue ;
            if(ans == -1 || ans > cos + cost[x - len]) {
                ans = cos + cost[x - len] ;
            }
         }
         for(long long j = 0 ; j < b[i].size() ; j ++ ) {
            long long cos = b[i][j].c ;
            long long len = b[i][j].len ;
            cost[len] = min(cost[len] , cos) ;
         }
    }
    if(ans > 999999999999) ans = -1 ;
    printf("%lld\n" , ans) ;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define vpi vector<pair <int, int> >
#define vi vector<int>
#define vl vector<ll>
#define vpl vector<pair<ll, ll> >
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define inf 100000000000000000

vl cost(200500,inf);

int main(){
	ios_base::sync_with_stdio(0);
	int n,x;
	cin >> n >> x;
	int days = x;
	vector<pair<pair<int, int>, pair<int, ll> > > op;

	for(int i=0; i<n; i++){
		int l,r;
		ll c;
		cin >> l >> r >> c;
		op.pb(mp(mp(l,-1), mp(r,c)));
		op.pb(mp(mp(r,1), mp(l,c)));
	}

	sort(op.begin(), op.end());

	ll len = op.size();
	ll ans = inf;
	for(ll i=0; i<len; i++){
		if(op[i].f.s == -1){
			int l = op[i].s.f-op[i].f.f+1;
			if(l<=x){
				ans = min(ans, cost[x-l]+op[i].s.s);
			}
		}
		else if(op[i].f.s == 1){
			int l = op[i].f.f-op[i].s.f+1;
			cost[l] = min(cost[l], op[i].s.s);
		}
	}
	if(ans == inf)cout<<-1;
	else
		cout<<ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define vpi vector<pair <int, int> >
#define vi vector<int>
#define vl vector<ll>
#define vpl vector<pair<ll, ll> >
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define inf 100000000000000000

vl cost(200500,inf);

int main(){
	ios_base::sync_with_stdio(0);
	int n,x;
	cin >> n >> x;
	int days = x;
	vector<pair<pair<int, int>, pair<int, ll> > > op;

	for(int i=0; i<n; i++){
		int l,r;
		ll c;
		cin >> l >> r >> c;
		op.pb(mp(mp(l,-1), mp(r,c)));
		op.pb(mp(mp(r,1), mp(l,c)));
	}

	sort(op.begin(), op.end());

	ll len = op.size();
	ll ans = inf;
	for(ll i=0; i<len; i++){
		if(op[i].f.s == -1){
			int l = op[i].s.f-op[i].f.f+1;
			ans = min(ans, cost[x-l]+op[i].s.s);
		}
		else if(op[i].f.s == 1){
			int l = op[i].f.f-op[i].s.f+1;
			cost[l] = min(cost[l], op[i].s.s);
		}
	}
	if(ans == inf)cout<<-1;
	else
		cout<<ans;
	return 0;
}


//============================================================================
// Name        : cf_422.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
	ios_base::sync_with_stdio(false);
	int n,x;
	cin >> n >> x;
	vector<pair<pair<int, int>, pair<int, ll> > > a(n+1);
	int i=0, j=0;

	while(i<n){
		cin >> a[i].first.first >> a[i].first.second >> a[i].second.second;
		a[i].second.first = a[i].first.second - a[i].first.first + 1;
		i++;
	}

	sort(a.begin(), a.end());
	//cout << a[1].second.second;
	ll ans = 10000000000;
	i=1;
	while(i<n){
		if(a[i].second.first < x){
			int temp = x - a[i].second.first;
			j = n;
			while(a[j].first.first > a[i].first.second){
				if(a[j].second.first == temp){
					if(ans > (a[i].second.second + a[j].second.second))
						ans = a[i].second.second + a[j].second.second;
				}

				j--;
				}
		}
		i++;
	}
	if(ans == 10000000000)
		cout << -1;
	else
		cout << ans;
	return 0;
}


//============================================================================
// Name        : 12.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
	ios_base::sync_with_stdio(false);
	int n,x;
	cin >> n >> x;
	vector<pair<pair<int, int>, pair<int, ll> > > a(n);
	int i=0, j=0;

	while(i<n){
		cin >> a[i].first.first >> a[i].first.second >> a[i].second.second;
		a[i].second.first = a[i].first.second - a[i].first.first + 1;
		i++;
	}

	sort(a.begin(), a.end());
	//cout << a[0].second.second;
	ll ans = 10000000000;
	i=0;
	while(i<n){
		if(a[i].second.first < x){
			j=n-1;
			while(a[j].first.first > a[i].first.second){
				if((a[i].second.first + a[j].second.first) == x){

					if(ans > (a[i].second.second + a[j].second.second))
						ans = a[i].second.second + a[j].second.second;
				}
				j--;
			}
		}
		i++;
	}
	if(ans == 10000000000)
		cout << -1;
	else
		cout << ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define vpi vector<pair <int, int> >
#define vi vector<int>
#define vl vector<ll>
#define vpl vector<pair<ll, ll> >
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define inf 100000000000000000

vl cost(20050,inf);

int main(){
	ios_base::sync_with_stdio(0);
	int n,x;
	cin >> n >> x;
	int days = x;
	vector<pair<pair<int, int>, pair<int, ll> > > op;

	for(int i=0; i<n; i++){
		int l,r;
		ll c;
		cin >> l >> r >> c;
		op.pb(mp(mp(l,-1), mp(r,c)));
		op.pb(mp(mp(r,1), mp(l,c)));
	}

	sort(op.begin(), op.end());

	ll len = op.size();
	ll ans = inf;
	for(ll i=0; i<len; i++){
		if(op[i].f.s == -1){
			int l = op[i].s.f-op[i].f.f+1;
			ans = min(ans, cost[l]+op[i].s.s);
		}
		else{
			int l = op[i].f.f-op[i].s.f+1;
			cost[l] = min(cost[l], op[i].s.s);
		}
	}
	if(ans == inf)cout<<-1;
	else
		cout<<ans;
	return 0;
}


//============================================================================
// Name        : cf_422.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
	ios_base::sync_with_stdio(false);
	ll n,x;
	cin >> n >> x;
	vector<pair<pair<int, int>, pair<int, ll> > > a(n);
	ll i=0, j=0;
	while(i<n){
		cin >> a[i].first.first >> a[i].first.second >> a[i].second.second;
		a[i].second.first = a[i].first.second - a[i].first.first + 1;
		i++;
	}
	sort(a.begin(), a.end());
	ll ans = 10000000000;

	i=0;
	while(i<n){
		if(a[i].second.first < x){
			j=i+1;
			while(j<n){
				int ri,rj,li,lj;
				ri = a[i].first.second;
				rj = a[i].first.second;
				li = a[i].first.first;
				lj = a[j].first.first;
				if((ri<lj or rj<li) and ((a[i].second.first+a[j].second.first) == x)){
					if(ans > (a[i].second.second + a[j].second.second))
						ans = a[i].second.second + a[j].second.second;
				}
				j++;
			}
		}
		i++;
	}
	if(ans == 10000000000)
		cout << -1;
	else
		cout << ans;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
	ios_base::sync_with_stdio(false);
	ll n,x;
	cin >> n >> x;
	vector<ll> l(n), r(n), cost(n);
	ll i=0, j=0;
	while(i<n){
		cin >> l[i] >> r[i] >> cost[i];
		i++;
	}

	ll ans = 10000000000;

	i=0;
	while(i<n){
		//cout << -1;
		if((r[i]-l[i] + 1) < x){
			j=i+1;
			while(j<n ){
				if((r[i]<l[j] or r[j]<l[i]) and ((r[i]+r[j]-l[i]-l[j]+2) == x)){
					if(ans > (cost[i]+cost[j]))
						ans = cost[i]+cost[j];
				}
				j++;
			}
		}
		i++;
	}
	if(ans == 10000000000)
		cout << -1;
	else
		cout << ans;
	return 0;
}


#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
struct node
{
    int l,r,t;
    long long pri;
}Q[MAXN];
int N,K;

bool cmp(node a, node b)
{
    if(a.t == b.t)
        return a.pri < b.pri;
    return a.t < b.t;
}

int binary1(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t < x){
            l = mid + 1;
        }
        else r = mid - 1;
    }
    return l;
}

int binary2(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t <= x){
            l = mid + 1;
        }
        else r = mid - 1;
    }
    return l;
}

long long work()
{
    int l=0,r=0;
    long long ans = (long long) 1<<32;
    for(int i = 1; i <= N; i++){
        int x = K - Q[i].t;
        if(x >= Q[i].t){
            l = binary1(x);
            r = binary2(x);
            for(int j = l; j < r; j++){
                if(Q[j].r < Q[i].l || Q[i].r < Q[j].l){
                    ans = min(ans,Q[i].pri+Q[j].pri);
                    break;
                }
            }
        }
    }
    return ans == (long long)1<<32? -1:ans;
}
int main()
{
    scanf("%d%d",&N,&K);
    for(int i = 1; i <= N; i++){
        scanf("%d%d%I64d",&Q[i].l,&Q[i].r,&Q[i].pri);
        Q[i].t = Q[i].r-Q[i].l+1;
    }
    sort(Q+1,Q+1+N,cmp);
    cout<<work()<<endl;
    return 0;
}


#include"vector"
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
const int maxx = 2e9+1;
vector <int> L[MAXN+1],R[MAXN+1];
int N,K,ans = maxx;
int dp[MAXN+1],pri[MAXN+1],t[MAXN+1];

int main()
{
    int l,r;
    scanf("%d%d",&N,&K);
    for(int i = 1; i < MAXN; i++)
        dp[i] = 1e9+1;
    for(int i = 1; i <= N; i++){
        scanf("%d%d%d",&l,&r,&pri[i]);
        L[l].push_back(i);
        R[r].push_back(i);
        t[i] = r-l+1;
    }
    for(int i = 1; i < MAXN; i++){
        for(int j = 0; j < L[i].size(); j++){
            int id = L[i][j];
            int x = K - t[id];
            if(x <= 0) continue;
            ans = min(dp[x]+pri[id],ans);
        }
        for(int j = 0; j < R[i].size(); j++){
            int id = R[i][j];
            dp[i] = min(dp[i],pri[id]);
        }
    }
    if(ans == maxx) ans = -1;
    cout<<ans<<endl;
    return 0;
}


#include"iostream"
#include"vector"
#include"cstdio"
#include"cstring"
using namespace std;
const int maxn = 2e5+7;
int ans,dp[maxn],t[maxn],pri[maxn],maxl;
vector <int>L[maxn],R[maxn];

int main()
{
    int l,r,n,m;
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++){
        scanf("%d%d%d",&l,&r,&pri[i]);
        t[i] = r-l+1;
        L[l].push_back(i);
        R[r].push_back(i);
        maxl = max(maxl,l);
    }

    for(int l = 1; l <= maxl; l++){
        for(int j = 0; j < L[l].size(); j++){
            int x = L[l][j];
            int k = m - t[x];
            if(k < 1 || (!dp[k])) continue;
            if(!ans) ans = dp[k]+pri[x];
            else ans = min(dp[k]+pri[x], ans);
        }

        for(int j = 0; j < R[l].size(); j++){
            int x = R[l][j];
            int ti = t[x];
            if(!dp[ti]) dp[ti] = pri[x];
            else dp[ti] = min(dp[ti],pri[x]);
        }
    }
    if(ans) cout<<ans<<endl;
    else cout<<"-1"<<endl;
    return 0;
}


#include"vector"
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
const int maxx = 2e9+2;
vector <int> L[MAXN+1],R[MAXN+1];
int N,K;
int t[MAXN+1];
long long ans = maxx,dp[MAXN+1],pri[MAXN+1];

int main()
{
    int l,r;
    scanf("%d%d",&N,&K);
    for(int i = 1; i < MAXN; i++)
        dp[i] = maxx;
    for(int i = 1; i <= N; i++){
        scanf("%d%d%I64d",&l,&r,&pri[i]);
        L[l].push_back(i);
        R[r].push_back(i);
        t[i] = r-l+1;
    }
    for(int i = 1; i < MAXN; i++){
        for(int j = 0; j < L[i].size(); j++){
            int id = L[i][j];
            int x = K - t[id];
            if(x <= 0) continue;
            ans = min(dp[x]+pri[id],ans);
        }
        for(int j = 0; j < R[i].size(); j++){
            int id = R[i][j];
            int x = t[id];
            dp[x] = min(dp[x],pri[id]);
        }
    }
    if(ans == maxx) ans = -1;
    cout<<ans<<endl;
    return 0;
}


#include"iostream"
#include"vector"
#include"cstdio"
#include"cstring"
using namespace std;
const int maxn = 2e5+7;
int ans,dp[maxn],t[maxn],pri[maxn],maxl;
vector <int>L[maxn],R[maxn];

int main()
{
    int l,r,n,m;
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++){
        scanf("%d%d%d",&l,&r,&pri[i]);
        t[i] = r-l+1;
        L[l].push_back(i);
        R[r].push_back(i);
        maxl = max(maxl,l);
    }

    for(int l = 1; l <= maxl; l++){
        for(int j = 0; j < L[l].size(); j++){
            int x = L[l][j];
            int k = m - t[x];
            if(k < 1 || (!dp[k])) continue;
            if(!ans) ans = dp[k]+pri[x];
            else ans = max(dp[k]+pri[x], ans);
        }

        for(int j = 0; j < R[l].size(); j++){
            int x = R[l][j];
            int ti = t[x];
            if(!dp[ti]) dp[ti] = pri[x];
            else dp[ti] = max(dp[ti],pri[x]);
        }
    }
    if(ans) cout<<ans<<endl;
    else cout<<"-1"<<endl;
    return 0;
}


#include"iostream"
#include"vector"
#include"cstdio"
#include"cstring"
using namespace std;
const int maxn = 2e5+7;
int ans,dp[maxn],t[maxn],pri[maxn],maxl;
vector <int>L[maxn],R[maxn];

int main()
{
    int l,r,n,m;
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++){
        scanf("%d%d%d",&l,&r,&pri[i]);
        t[i] = r-l+1;
        L[l].push_back(i);
        R[r].push_back(i);
        maxl = max(maxl,l);
    }

    for(int l = 1; l <= maxl; l++){
        for(int j = 0; j < L[l].size(); j++){
            int x = L[l][j];
            int k = m - t[x];
            if(k < 1) continue;
            if(!ans) ans = dp[k]+pri[x];
            else ans = max(dp[k]+pri[x], ans);
        }

        for(int j = 0; j < R[l].size(); j++){
            int x = R[l][j];
            int ti = t[x];
            if(!dp[ti]) dp[ti] = pri[x];
            else dp[ti] = max(dp[ti],pri[x]);
        }
    }
    if(ans) cout<<ans<<endl;
    else cout<<"-1"<<endl;
    return 0;
}


#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
struct node
{
    int l,r,t;
    long long pri;
}Q[MAXN];
int N,K;

bool cmp(node a, node b)
{
    if(a.t == b.t)
        return a.pri > b.pri;
    return a.t > b.t;
}

int binary1(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t < x){
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return r;
}

int binary2(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t <= x){
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return r;
}

long long work()
{
    int l=0,r=0;
    long long ans = (long long) 1<<32;
    for(int i = 1; i <= N; i++){
        int x = K - Q[i].t;
        if(x <= Q[i].t){
            r = binary1(x);
            l = binary2(x);
            for(int j = r; j > l; j--){
                if(Q[j].r < Q[i].l || Q[i].r < Q[j].l){
                    ans = min(ans,Q[i].pri+Q[j].pri);
                    break;
                }
            }
        }
    }
    return ans == (long long)1<<32? -1:ans;
}
int main()
{
    scanf("%d%d",&N,&K);
    for(int i = 1; i <= N; i++){
        scanf("%d%d%I64d",&Q[i].l,&Q[i].r,&Q[i].pri);
        Q[i].t = Q[i].r-Q[i].l+1;
    }
    sort(Q+1,Q+1+N,cmp);
    cout<<work()<<endl;
    return 0;
}


#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
struct node
{
    int l,r,t;
    long long pri;
}Q[MAXN];
int N,K;

bool cmp(node a, node b)
{
    return a.t < b.t;
}

int binary1(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t < x){
            l = mid + 1;
        }
        r = mid - 1;
    }
    return l;
}

int binary2(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t <= x){
            l = mid + 1;
        }
        else r = mid - 1;
    }
    return l;
}

long long work()
{
    int l=0,r=0;
    long long ans = (long long) 1<<32;
    for(int i = 1; i <= N; i++){
        int x = K - Q[i].t;
        if(x >= Q[i].t){
            l = binary1(x);
            r = binary2(x);
        }
        for(int j = l; j < r; j++){
            if(Q[j].r < Q[i].l || Q[i].r < Q[j].l)
            ans = min(ans,Q[i].pri+Q[j].pri);
        }
    }
    return ans == (long long)1<<32? -1:ans;
}
int main()
{
    scanf("%d%d",&N,&K);
    for(int i = 1; i <= N; i++){
        scanf("%d%d%I64d",&Q[i].l,&Q[i].r,&Q[i].pri);
        Q[i].t = Q[i].r-Q[i].l+1;
    }
    sort(Q+1,Q+1+N,cmp);
    cout<<work()<<endl;
    return 0;
}


#include"vector"
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
const int maxx = 2e9+1;
vector <int> L[MAXN+1],R[MAXN+1];
int N,K,ans = maxx;
int dp[MAXN+1],pri[MAXN+1],t[MAXN+1];

int main()
{
    int l,r;
    scanf("%d%d",&N,&K);
    for(int i = 1; i < MAXN; i++)
        dp[i] = 1e9+1;
    for(int i = 1; i <= N; i++){
        scanf("%d%d%d",&l,&r,&pri[i]);
        L[l].push_back(i);
        R[r].push_back(i);
        t[i] = r-l+1;
    }
    for(int i = 1; i < MAXN; i++){
        for(int j = 0; j < L[i].size(); j++){
            int id = L[i][j];
            int x = K - t[id];
            if(x <= 0) continue;
            ans = min(dp[x]+pri[id],ans);
        }
        for(int j = 0; j < R[i].size(); j++){
            int id = R[i][j];
            int x = t[id];
            dp[x] = min(dp[x],pri[id]);
        }
    }
    if(ans == maxx) ans = -1;
    cout<<ans<<endl;
    return 0;
}


#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
struct node
{
    int l,r,t;
    long long pri;
}Q[MAXN];
int N,K;

bool cmp(node a, node b)
{
    if(a.t == b.t)
        return a.pri < b.pri;
    return a.t > b.t;
}

int binary1(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t < x){
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return r;
}

int binary2(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t <= x){
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return r;
}

long long work()
{
    int l=0,r=0;
    long long ans = (long long) 1<<32;
    for(int i = 1; i <= N; i++){
        int x = K - Q[i].t;
        if(x <= Q[i].t){
            r = binary1(x);
            l = binary2(x);
            for(int j = r; j > l; j--){
                if(Q[j].r < Q[i].l || Q[i].r < Q[j].l){
                    ans = min(ans,Q[i].pri+Q[j].pri);
                    break;
                }
            }
        }
    }
    return ans == (long long)1<<32? -1:ans;
}
int main()
{
    scanf("%d%d",&N,&K);
    for(int i = 1; i <= N; i++){
        scanf("%d%d%I64d",&Q[i].l,&Q[i].r,&Q[i].pri);
        Q[i].t = Q[i].r-Q[i].l+1;
    }
    sort(Q+1,Q+1+N,cmp);
    cout<<work()<<endl;
    return 0;
}


#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
const int MAXN = 2e5+3;
struct node
{
    int l,r,t;
    long long pri;
}Q[MAXN];
int N,K;

bool cmp(node a, node b)
{
    if(a.t == b.t)
        return a.pri < b.pri;
    return a.t > b.t;
}

int binary1(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t < x){
            l = mid + 1;
        }
        else r = mid - 1;
    }
    return l;
}

int binary2(int x)
{
    int l = 1, r = N;
    while(l<=r)
    {
        int mid = l+r>>1;
        if(Q[mid].t <= x){
            l = mid + 1;
        }
        else r = mid - 1;
    }
    return l;
}

long long work()
{
    int l=0,r=0;
    long long ans = (long long) 1<<32;
    for(int i = 1; i <= N; i++){
        int x = K - Q[i].t;
        if(x <= Q[i].t){
            l = binary1(x);
            r = binary2(x);
            for(int j = l; j < r; j++){
                if(Q[j].r < Q[i].l || Q[i].r < Q[j].l){
                    ans = min(ans,Q[i].pri+Q[j].pri);
                    break;
                }
            }
        }
    }
    return ans == (long long)1<<32? -1:ans;
}
int main()
{
    scanf("%d%d",&N,&K);
    for(int i = 1; i <= N; i++){
        scanf("%d%d%I64d",&Q[i].l,&Q[i].r,&Q[i].pri);
        Q[i].t = Q[i].r-Q[i].l+1;
    }
    sort(Q+1,Q+1+N,cmp);
    cout<<work()<<endl;
    return 0;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii a[N];
int minc[N];
int ans;
bool kt[N];

int main()  0
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
        cin >> a[i].X.X >> a[i].X.Y >> a[i].Y;
    sort(a + 1, a+ n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (a[j + 1].X.Y < a[i].X.X)
        {
            ++j, minc[a[j].X.Y - a[j].X.X + 1] = min(minc[a[j].X.Y - a[j].X.X + 1], a[j].Y);
            kt[a[j].X.Y - a[j].X.X + 1] = true;
        }
        int t = a[i].X.Y - a[i].X.X + 1;
        if (kt[x - t])
        ans = min(ans, a[i].Y + minc[x - t]);
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii r[N];
iii l[N];
int minc[N];
int ans;
bool kt[N];

int main()
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
    {
        int u, v, c;
        cin >> u >> v>> c;
        l[i].X.X = u;
        l[i].X.Y = v - u + 1;
        l[i].Y = c;
        r[i].X.X = v;
        r[i].X.Y = v - u + 1;
        r[i].Y = c;
    }
    sort(l + 1, l + n + 1);
    sort(r + 1, r + n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (r[j + 1].X.X <= l[i].X.X)
        {
            ++j, minc[r[j].X.Y] = min(minc[r[j].X.Y], r[j].Y);
            kt[r[j].X.Y] = true;
        }
        int t = l[i].X.Y;
        if (x >= t && kt[x - t])
        {
        ans = min(ans, l[i].Y + minc[x - t]);
        if (n == 200000 && x == 640) cout << x - t << ' ';
        }
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii r[N];
iii l[N];
int minc[N];
int ans;
bool kt[N];

int main()
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
    {
        int u, v, c;
        cin >> u >> v>> c;
        l[i].X.X = u;
        l[i].X.Y = v - u + 1;
        l[i].Y = c;
        r[i].X.X = v;
        r[i].X.Y = v - u + 1;
        r[i].Y = c;
    }
    sort(l + 1, l + n + 1);
    sort(r + 1, r + n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (r[j + 1].X.X <= l[i].X.X)
        {
            ++j, minc[r[j].X.Y] = min(minc[r[j].X.Y], r[j].Y);
            kt[r[j].X.Y] = true;
        }
        int t = l[i].X.Y;
        if (x >= t && kt[x - t])
        {
        ans = min(ans, l[i].Y + minc[x - t]);
        if (n == 200000) cout << x - t << ' ';
        }
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii r[N];
iii l[N];
int minc[N];
int ans;
bool kt[N];

int main()
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
    {
        int u, v, c;
        cin >> u >> v>> c;
        l[i].X.X = u;
        l[i].X.Y = v - u + 1;
        l[i].Y = c;
        r[i].X.X = v;
        r[i].X.Y = v - u + 1;
        r[i].Y = c;
    }
    sort(l + 1, l + n + 1);
    sort(r + 1, r + n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (r[j + 1].X.X <= l[i].X.X)
        {
            ++j, minc[r[j].X.Y] = min(minc[r[j].X.Y], r[j].Y);
            kt[r[j].X.Y] = true;
        }
        int t = l[i].X.Y;
        if (x >= t && kt[x - t])
        ans = min(ans, l[i].Y + minc[x - t]);
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii a[N];
int minc[N];
int ans;
bool kt[N];

int main()
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
        cin >> a[i].X.X >> a[i].X.Y >> a[i].Y;
    sort(a + 1, a+ n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (a[j + 1].X.Y <= a[i].X.X)
        {
            ++j, minc[a[j].X.Y - a[j].X.X + 1] = min(minc[a[j].X.Y - a[j].X.X + 1], a[j].Y);
            kt[a[j].X.Y - a[j].X.X + 1] = true;
        }
        int t = a[i].X.Y - a[i].X.X + 1;
        if (kt[x - t])
        ans = min(ans, a[i].Y + minc[x - t]);
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii a[N];
int minc[N];
int ans;
bool kt[N];

int main()
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
        cin >> a[i].X.X >> a[i].X.Y >> a[i].Y;
    sort(a + 1, a+ n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (a[j + 1].X.Y < a[i].X.X)
        {
            ++j, minc[a[j].X.Y - a[j].X.X + 1] = min(minc[a[j].X.Y - a[j].X.X + 1], a[j].Y);
            kt[a[j].X.Y - a[j].X.X + 1] = true;
        }
        int t = a[i].X.Y - a[i].X.X + 1;
        if (kt[x - t])
        ans = min(ans, a[i].Y + minc[x - t]);
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
const int N = 2e5 + 1;
typedef pair <int, int> ii;
typedef pair <ii, int> iii;
int n, x;
iii r[N];
iii l[N];
int minc[N];
int ans;
bool kt[N];

int main()
{
    ans = INT_MAX;
    memset(minc, 127, sizeof(minc));
    memset(kt, false, sizeof(kt));
    cin >> n >> x;
    for (int i = 1; i <= n; ++i)
    {
        int u, v, c;
        cin >> u >> v>> c;
        l[i].X.X = u;
        l[i].X.Y = v - u + 1;
        l[i].Y = c;
        r[i].X.X = v;
        r[i].X.Y = v - u + 1;
        r[i].Y = c;
    }
    sort(l + 1, l + n + 1);
    sort(r + 1, r + n + 1);
    int j = 0;
    for (int i = 1; i <= n; ++i)
    {
        while (r[j + 1].X.X < l[i].X.X)
        {
            ++j, minc[r[j].X.Y] = min(minc[r[j].X.Y], r[j].Y);
            kt[r[j].X.Y] = true;
        }
        int t = l[i].X.Y;
        if (x >= t && kt[x - t])
        {
        ans = min(ans, l[i].Y + minc[x - t]);
       // if (n == 200000 && x == 640) cout << x - t << ' ';
        }
    }
    if (ans == INT_MAX) cout <<-1;
    else
    cout << ans;
}


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<cmath>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
const int maxn = 1e6+5;
const int ff = 0x3f3f3f3f;
struct node
{
	int o;
	int e;
	int l;
	int r;
	ll cost;
};

int n,x;
struct node a[maxn];
ll sum[maxn];

bool cmp(struct node p,struct node q)
{
	return p.e< q.e;
}

int main()
{
	cin>>n>>x;

	int l,r,c;
	int cnt = 0;
	for(int i = 1;i<= n;i++)
	{
		scanf("%d %d %d",&l,&r,&c);
		a[++cnt].o = 1;
		a[cnt].r = r;
		a[cnt].l = l;
		a[cnt].e = l;
		a[cnt].cost = c;
		a[++cnt].o = 2;
		a[cnt].l = l;
		a[cnt].r = r;
		a[cnt].e = r;
		a[cnt].cost = c;
	}

	sort(a+1,a+n+1,cmp);
	for(int i = 1;i<= 2e5+1;i++)
		sum[i] = 1e15;

	ll ans = 1e16;
	for(int i = 1;i<= cnt;i++)
	{
		if(a[i].o == 1)
		{
			if(x - (a[i].r-a[i].l+1)> 0)
			{
				ans = min(sum[x - (a[i].r-a[i].l+1)]+a[i].cost,ans);
			}
		}
		else
		{
			sum[a[i].r - a[i].l+1] = min(sum[a[i].r - a[i].l+1],a[i].cost);
		}
	}

	if(ans >= 1e15)
		cout<<-1<<endl;
	else
		cout<<ans<<endl;
	return 0;
}