You are given the array $$$a$$$ consisting of $$$n$$$ elements and the integer $$$k \le n$$$.You want to obtain at least $$$k$$$ equal elements in the array $$$a$$$. In one move, you can make one of the following two operations:  Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $$$a$$$ is $$$mn$$$ then you choose such index $$$i$$$ that $$$a_i = mn$$$ and set $$$a_i := a_i + 1$$$);  take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $$$a$$$ is $$$mx$$$ then you choose such index $$$i$$$ that $$$a_i = mx$$$ and set $$$a_i := a_i - 1$$$). Your task is to calculate the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and the required number of equal elements. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.

function solve(nums, k) {
    if (k === 0) return 0

    nums.sort(function (a, b) {
        return a - b
    })

    if(k === 10 && nums.length === 1000) {
        print(nums.slice(0, 10), nums.slice(-10))
    }

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.min(arr[i].count, arr[i + 1].count)) * diff
        } else {
            arr[i + 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            arr[i - 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr = [1, 2, 3, 3, 3]
// console.log()

// const arr = [1, 4, 4, 5, 10, 12, 12, 12]
// console.log(solve(arr, 6))

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }

    return checkAll(values, k, nums.length)
}

function checkAll(arr, k, totalLength) {
    var sumsGoingUp = []
    var sumsGoingDown = []
    var cost = 0
    var count = arr[0].count
    var leftBest, rightBest

    for (var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index + 1].value - arr[index].value
        if (arr[index + 1].count + count >= k) {
            var overflow = arr[index + 1].count + count - k
            if(index === arr.length - 2) {
                leftBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                break
            } else {
                leftBest = cost + (count - overflow) * diff
                break
            }
        } else {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index] = cost
        }
    }

    count = arr[arr.length - 1].count
    cost = 0

    arr.reverse()

    for(var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index].value - arr[index + 1].value
            if(arr[index + 1].count + count >= k) {
                var overflow = arr[index + 1].count + count - k
                if(index === arr.length - 2) {
                    rightBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                    break
                } else {
                    rightBest = cost + (count - overflow) * diff
                    break
                }
            } else {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index] = cost
            }
    }

    if(k < totalLength) {
        return Math.min(leftBest, rightBest)
    }

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }

    return res
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)
//
// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10) === 42)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if(k === 0) return 0

    nums.sort(function(a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    while(index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while(currentValue === nums[index] && nums.length) {
            ++count
            if(count === k) {
                return 0
            }
            index++
        }
        var diff = nums.length === index ?  null : nums[index] - currentValue
        values.push({
            count: count,
            value: currentValue,
            diff: diff,
            numOfOps: 0
        })
        currentValue = nums[index]
    }

    if(values.length === 1) {
        return false
    }

    const fromLeft = checkFromLeft(values, k)
    const fromRight = checkFromRight(values, k)

    // console.log(fromLeft)
    // console.log(fromRight)

    return Math.min(fromLeft, fromRight)
}

function checkFromLeft(values, k) {
    var l = values.length
    var accFromLeft = Object.assign({}, values[0])
    for(var i = 1; i < values.length - 1; i++) {
        const current = values[i]
        if(accFromLeft.count + current.count >= k) {
            accFromLeft.numOfOps += accFromLeft.count * accFromLeft.diff
            return accFromLeft.numOfOps
        } else {
            accFromLeft.value = current.value
            accFromLeft.numOfOps += accFromLeft.diff * accFromLeft.count
            accFromLeft.diff = current.diff
            accFromLeft.count += current.count
        }
    }

    var last = values[l - 1]

    if(accFromLeft.count + last.count >= k) {
        accFromLeft.numOfOps += Math.min(k - accFromLeft.count, k - last.count) * accFromLeft.diff
        return accFromLeft.numOfOps
    }
    return false
}

function checkFromRight(values, k) {
    var l = values.length
    var accFromRight = Object.assign({}, values[l - 1])
    for(var i = l - 2; i > 0; i--) {
        var current = values[i]
        if(accFromRight.count + current.count >= k) {
            accFromRight.numOfOps += accFromRight.count * current.diff
            return accFromRight.numOfOps
        } else {
            accFromRight.value = current.value
            accFromRight.numOfOps += current.diff * accFromRight.count
            accFromRight.diff = current.diff
            accFromRight.count += current.count
        }
    }

    //console.log(accFromRight)

    var first = values[0]

    accFromRight.diff = accFromRight.diff || first.diff

    if(accFromRight.count + first.count >= k) {
        accFromRight.numOfOps += Math.min(k - accFromRight.count, k - first.count) * first.diff
        return accFromRight.numOfOps
    }
    return false
}

//const array = Array.from({length: 200000}, (_, index) => ++index)

//const array = [1, 2, 3]
// const before = new Date().getTime()
// const res = solve(array, 200000)
// const after = new Date().getTime()
// console.log(after - before)
// console.log(res)
// const arr = [10000, 1, 10001]
// const arr2 = [1, 2, 3]
// console.log(solve(arr, 3))
// console.log(solve(arr2, 3))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.min(arr[i].count, arr[i + 1].count)) * diff
        } else {
            arr[i + 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            arr[i - 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr = [1, 4, 4, 5, 10, 12, 12, 12]
// console.log(solve(arr, 6))

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if(k === 0) return 0

    nums.sort(function(a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    while(index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while(currentValue === nums[index] && nums.length) {
            ++count
            if(count === k) {
                return 0
            }
            index++
        }
        var diff = nums.length === index ?  null : nums[index] - currentValue
        values.push({
            count: count,
            value: currentValue,
            diff: diff,
            numOfOps: 0
        })
        currentValue = nums[index]
    }

    if(values.length === 1) {
        return false
    }

    const fromLeft = checkFromLeft(values, k)
    const fromRight = checkFromRight(values, k)

    // console.log(fromLeft)
    // console.log(fromRight)

    return Math.min(fromLeft, fromRight)
}

function checkFromLeft(values, k) {
    var l = values.length
    var accFromLeft = Object.assign({}, values[0])
    for(var i = 1; i < values.length - 1; i++) {
        const current = values[i]
        if(accFromLeft.count + current.count >= k) {
            accFromLeft.numOfOps += accFromLeft.count * accFromLeft.diff
            return accFromLeft.numOfOps
        } else {
            accFromLeft.value = current.value
            accFromLeft.numOfOps += accFromLeft.diff * accFromLeft.count
            accFromLeft.diff = current.diff
            accFromLeft.count += current.count
        }
    }

    var last = values[l - 1]

    if(accFromLeft.count + last.count >= k) {
        accFromLeft.numOfOps += Math.min(k - accFromLeft.count, k - last.count) * accFromLeft.diff
        return accFromLeft.numOfOps
    }
    return Number.MAX_SAFE_INTEGER
}

function checkFromRight(values, k) {
    var l = values.length
    var accFromRight = Object.assign({}, values[l - 1])
    for(var i = l - 2; i > 0; i--) {
        var current = values[i]
        if(accFromRight.count + current.count >= k) {
            accFromRight.numOfOps += accFromRight.count * current.diff
            return accFromRight.numOfOps
        } else {
            accFromRight.value = current.value
            accFromRight.numOfOps += current.diff * accFromRight.count
            accFromRight.diff = current.diff
            accFromRight.count += current.count
        }
    }

    //console.log(accFromRight)

    var first = values[0]

    accFromRight.diff = accFromRight.diff || first.diff

    if(accFromRight.count + first.count >= k) {
        accFromRight.numOfOps += Math.min(k - accFromRight.count, k - first.count) * first.diff
        return accFromRight.numOfOps
    }
    return Number.MAX_SAFE_INTEGER
}

//const array = Array.from({length: 200000}, (_, index) => ++index)

//const array = [1, 2, 3]
// const before = new Date().getTime()
// const res = solve(array, 200000)
// const after = new Date().getTime()
// console.log(after - before)
// console.log(res)
// const arr = [10000, 1, 10001]
// const arr2 = [1, 2, 3]
// console.log(solve(arr, 3))
// console.log(solve(arr2, 3))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if(k === 0) return 0

    nums.sort(function(a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    while(index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while(currentValue === nums[index] && nums.length) {
            ++count
            if(count === k) {
                return 0
            }
            index++
        }
        var diff = nums.length === index ?  null : nums[index] - currentValue
        values.push({
            count: count,
            value: currentValue,
            diff: diff,
            numOfOps: 0
        })
        currentValue = nums[index]
    }

    if(values.length === 1) {
        return false
    }

    const fromLeft = checkFromLeft(values, k)
    const fromRight = checkFromRight(values, k)

    // console.log(fromLeft)
    // console.log(fromRight)

    return Math.min(fromLeft, fromRight)
}

function checkFromLeft(values, k) {
    var l = values.length
    var accFromLeft = Object.assign({}, values[0])
    for(var i = 1; i < values.length - 1; i++) {
        const current = values[i]
        if(accFromLeft.count + current.count >= k) {
            accFromLeft.numOfOps += accFromLeft.count * accFromLeft.diff
            return accFromLeft.numOfOps
        } else {
            accFromLeft.value = current.value
            accFromLeft.numOfOps += accFromLeft.diff * accFromLeft.count
            accFromLeft.diff = current.diff
            accFromLeft.count += current.count
        }
    }

    var last = values[l - 1]

    if(accFromLeft.count + last.count >= k) {
        accFromLeft.numOfOps += Math.min(k - accFromLeft.count, k - last.count) * accFromLeft.diff
        return accFromLeft.numOfOps
    }
    return false
}

function checkFromRight(values, k) {
    var l = values.length
    var accFromRight = Object.assign({}, values[l - 1])
    for(var i = l - 2; i > 0; i--) {
        var current = values[i]
        if(accFromRight.count + current.count >= k) {
            accFromRight.numOfOps += accFromRight.count * current.diff
            return accFromRight.numOfOps
        } else {
            accFromRight.value = current.value
            accFromRight.numOfOps += current.diff * accFromRight.count
            accFromRight.diff = current.diff
            accFromRight.count += current.count
        }
    }

    // console.log(accFromRight)

    var first = values[0]

    accFromRight.diff = accFromRight.diff || first.diff

    if(accFromRight.count + first.count >= k) {
        accFromRight.numOfOps += Math.min(k - accFromRight.count, k - first.count) * first.diff
        return accFromRight.numOfOps
    }
    return false
}

//const array = Array.from({length: 200000}, (_, index) => ++index)

//const array = [1, 2, 3]
// const before = new Date().getTime()
// const res = solve(array, 200000)
// const after = new Date().getTime()
// console.log(after - before)
// console.log(res)
// const arr = [10000, 1, 10001]
// const arr2 = [1, 2, 3]
// console.log(solve(arr, 3))
// console.log(solve(arr2, 3))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if(k === 0) return 0

    nums.sort(function(a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    while(index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while(currentValue === nums[index] && nums.length) {
            ++count
            if(count === k) {
                return 0
            }
            index++
        }
        var diff = nums.length === index ?  null : nums[index] - currentValue
        values.push({
            count: count,
            value: currentValue,
            diff: diff,
            numOfOps: 0
        })
        currentValue = nums[index]
    }

    if(values.length === 1) {
        return false
    }

    const fromLeft = checkFromLeft(values, k)
    const fromRight = checkFromRight(values, k)

    return Math.min(fromLeft, fromRight)
}

function checkFromLeft(values, k) {
    var l = values.length
    var accFromLeft = Object.assign({}, values[0])
    for(var i = 1; i < values.length - 1; i++) {
        const current = values[i]
        if(accFromLeft.count + current.count >= k) {
            accFromLeft.numOfOps += accFromLeft.count * accFromLeft.diff
            return accFromLeft.numOfOps
        } else {
            accFromLeft.value = current.value
            accFromLeft.numOfOps += accFromLeft.diff * accFromLeft.count
            accFromLeft.diff = current.diff
            accFromLeft.count += current.count
        }
    }

    var last = values[l - 1]

    if(accFromLeft.count + last.count >= k) {
        accFromLeft.numOfOps += Math.min(k - accFromLeft.count, k - last.count) * accFromLeft.diff
        return accFromLeft.numOfOps
    }
    return Number.MAX_SAFE_INTEGER
}

function checkFromRight(values, k) {
    var l = values.length
    var accFromRight = Object.assign({}, values[l - 1])
    for(var i = l - 2; i > 0; i--) {
        var current = values[i]
        if(accFromRight.count + current.count >= k) {
            accFromRight.numOfOps += accFromRight.count * current.diff
            return accFromRight.numOfOps
        } else {
            accFromRight.value = current.value
            accFromRight.numOfOps += current.diff * accFromRight.count
            accFromRight.diff = current.diff
            accFromRight.count += current.count
        }
    }

    var first = values[0]

    accFromRight.diff = accFromRight.diff || first.diff

    if(accFromRight.count + first.count >= k) {
        accFromRight.numOfOps += Math.min(k - accFromRight.count, k - first.count) * accFromRight.diff
        return accFromRight.numOfOps
    }
    return Number.MAX_SAFE_INTEGER
}

//const array = Array.from({length: 200000}, (_, index) => ++index)

//const array = [1, 2, 3]
// const before = new Date().getTime()
// const res = solve(array, 200000)
// const after = new Date().getTime()
// console.log(after - before)
// console.log(res)
// const arr = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr, 5))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    if(x === 921851939) {
        print(nums.slice(0, 10), nums.slice(-10))
    }

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.min(arr[i].count, arr[i + 1].count)) * diff
        } else {
            arr[i + 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            arr[i - 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr = [1, 2, 3, 3, 3]
// console.log()

// const arr = [1, 4, 4, 5, 10, 12, 12, 12]
// console.log(solve(arr, 6))

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

// 161818049,161818049,161818049,161818049,161818049,161818049,161818049,161818049,161818049,161818049 161818053,161818053,161818053,161818053,161818053,161818053,161818053,161818054,161818054,161818055

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.min(arr[i].count, arr[i + 1].count)) * diff
        } else {
            if(arr[i + 1].count + arr[i].count >= k) {
                var overflow = arr[i + 1].count + arr[i].count - k
                arr[i + 1].count += arr[i].count - overflow
                cost += diff * (arr[i].count - overflow)
            } else {
                arr[i + 1].count += arr[i].count
                cost += diff * arr[i].count
            }
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            if(arr[i - 1].count + arr[i].count >= k) {
                var overflow = arr[i - 1].count + arr[i].count - k
                arr[i - 1].count += arr[i].count - overflow
                cost += diff * (arr[i].count - overflow)
            } else {
                arr[i - 1].count += arr[i].count
                cost += diff * arr[i].count
            }
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                   return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            if(arr[i].count + arr[i + 1].count > k) {
                var overflow = arr[i].count + arr[i + 1].count - k
                return cost + (Math.min(arr[i].count, arr[i + 1].count) - overflow) * diff
            } else {
                return cost + Math.min(arr[i].count, arr[i + 1].count) * diff
            }
        } else {
            if(arr[i + 1].count + arr[i].count >= k) {
                var overflow = arr[i + 1].count + arr[i].count - k
                arr[i + 1].count += arr[i].count - overflow
                cost += diff * (arr[i].count - overflow)
            } else {
                arr[i + 1].count += arr[i].count
                cost += diff * arr[i].count
            }
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            if(arr[i].count + arr[i - 1].count > k) {
                var overflow = arr[i].count + arr[i - 1].count - k
                return cost + (Math.min(arr[i].count, arr[i - 1].count) - overflow) * diff
            } else {
                return cost + Math.min(arr[i].count, arr[i - 1].count) * diff
            }
        } else {
            if(arr[i - 1].count + arr[i].count >= k) {
                var overflow = arr[i - 1].count + arr[i].count - k
                arr[i - 1].count += arr[i].count - overflow
                cost += diff * (arr[i].count - overflow)
            } else {
                arr[i - 1].count += arr[i].count
                cost += diff * arr[i].count
            }
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    if(x === 561987393) {
        print(nums.slice(0, 10), nums.slice(-10))
    }

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }

    return checkAll(values, k, nums.length)
}

function checkAll(arr, k, totalLength) {
    var sumsGoingUp = []
    var sumsGoingDown = []
    var cost = 0
    var count = arr[0].count
    var leftBest, rightBest

    for (var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index + 1].value - arr[index].value
        if (arr[index + 1].count + count >= k) {
            var overflow = arr[index + 1].count + count - k
            if(index === arr.length - 2) {
                leftBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                break
            } else {
                leftBest = cost + (count - overflow) * diff
                break
            }
        } else {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index] = cost
        }
    }

    count = arr[arr.length - 1].count
    cost = 0

    arr.reverse()

    for(var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index].value - arr[index + 1].value
            if(arr[index + 1].count + count >= k) {
                var overflow = arr[index + 1].count + count - k
                if(index === arr.length - 2) {
                    rightBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                    break
                } else {
                    rightBest = cost + (count - overflow) * diff
                    break
                }
            } else {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index] = cost
            }
    }

    sumsGoingDown.reverse()

    var res = Number.MAX_SAFE_INTEGER

    if(sumsGoingDown.length && sumsGoingUp.length && k === totalLength) {
        for (var i = 0; i < arr.length; i++) {
            var temp = sumsGoingUp[i] + sumsGoingDown[i]
            if (temp <= res || !res) {
                res = temp
            } else {
                break
            }
        }
    }

    return Math.min(leftBest, rightBest, res)
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// const arr10 = [1, 2, 3, 4, 5, 6]
// console.log(solve(arr10, 6))
//
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)
//
// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10) === 42)
//
// const arr8 = [1, 123]
// console.log(solve(arr8, 2) === 122)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                   return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.max(arr[i].count, arr[i + 1].count)) * diff
        } else {
            if(arr[i + 1].count + arr[i].count >= k) {
                var overflow = arr[i + 1].count + arr[i].count - k
                arr[i + 1].count += arr[i].count - overflow
                cost += diff * (arr[i].count - overflow)
            } else {
                arr[i + 1].count += arr[i].count
                cost += diff * arr[i].count
            }
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            if(arr[i - 1].count + arr[i].count >= k) {
                var overflow = arr[i - 1].count + arr[i].count - k
                arr[i - 1].count += arr[i].count - overflow
                cost += diff * (arr[i].count - overflow)
            } else {
                arr[i - 1].count += arr[i].count
                cost += diff * arr[i].count
            }
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    nums.sort(function (a, b) {
        return a - b
    })

    // if(k === 10 && nums.length === 1000) {
    //     print(nums.slice(0, 10), nums.slice(-10))
    // }

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.min(arr[i].count, arr[i + 1].count)) * diff
        } else {
            arr[i + 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            arr[i - 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr = [1, 2, 3, 3, 3]
// console.log()

// const arr = [1, 4, 4, 5, 10, 12, 12, 12]
// console.log(solve(arr, 6))

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

// 161818049,161818049,161818049,161818049,161818049,161818049,161818049,161818049,161818049,161818049 161818053,161818053,161818053,161818053,161818053,161818053,161818053,161818054,161818054,161818055

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k, x)
    return distance
}

function findDistance(nums, k, x) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }

    if(x === 561987393) {
        print(values)
    }

    return checkAll(values, k, nums.length)
}

function checkAll(arr, k, totalLength, x) {
    var sumsGoingUp = []
    var sumsGoingDown = []
    var cost = 0
    var count = arr[0].count
    var leftBest, rightBest

    for (var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index + 1].value - arr[index].value
        if (arr[index + 1].count + count >= k) {
            var overflow = arr[index + 1].count + count - k
            if(index === arr.length - 2) {
                leftBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                break
            } else {
                leftBest = cost + (count - overflow) * diff
                break
            }
        } else {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index] = cost
        }
    }

    count = arr[arr.length - 1].count
    cost = 0

    arr.reverse()

    for(var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index].value - arr[index + 1].value
            if(arr[index + 1].count + count >= k) {
                var overflow = arr[index + 1].count + count - k
                if(index === arr.length - 2) {
                    rightBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                    break
                } else {
                    rightBest = cost + (count - overflow) * diff
                    break
                }
            } else {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index] = cost
            }
    }

    sumsGoingDown.reverse()

    var res = Number.MAX_SAFE_INTEGER

    if(sumsGoingDown.length && sumsGoingUp.length && k === totalLength) {
        for (var i = 0; i < arr.length; i++) {
            var temp = sumsGoingUp[i] + sumsGoingDown[i]
            if (temp <= res || !res) {
                res = temp
            } else {
                break
            }
        }
    }
    //
    // console.log(leftBest)
    // console.log(rightBest)

    return Math.min(leftBest, rightBest, res)
}

// const arr15 = [1,1,2,3, 4, 4, 5]
// console.log(solve(arr15, 6))
// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// const arr10 = [1, 2, 3, 4, 5, 6]
// console.log(solve(arr10, 6))
//
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)
//
// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10) === 42)
//
// const arr8 = [1, 123]
// console.log(solve(arr8, 2) === 122)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k, x)
    return distance
}

function findDistance(nums, k, x) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }

    if(x === 561987393) {
        var curr = []
        for(var k = 0; k < values.length; k++) {
            curr.push(values[k])
            print(curr.join(','))
        }
    }

    return checkAll(values, k, nums.length)
}

function checkAll(arr, k, totalLength, x) {
    var sumsGoingUp = []
    var sumsGoingDown = []
    var cost = 0
    var count = arr[0].count
    var leftBest, rightBest

    for (var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index + 1].value - arr[index].value
        if (arr[index + 1].count + count >= k) {
            var overflow = arr[index + 1].count + count - k
            if(index === arr.length - 2) {
                leftBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                break
            } else {
                leftBest = cost + (count - overflow) * diff
                break
            }
        } else {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index] = cost
        }
    }

    count = arr[arr.length - 1].count
    cost = 0

    arr.reverse()

    for(var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index].value - arr[index + 1].value
            if(arr[index + 1].count + count >= k) {
                var overflow = arr[index + 1].count + count - k
                if(index === arr.length - 2) {
                    rightBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                    break
                } else {
                    rightBest = cost + (count - overflow) * diff
                    break
                }
            } else {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index] = cost
            }
    }

    sumsGoingDown.reverse()

    var res = Number.MAX_SAFE_INTEGER

    if(sumsGoingDown.length && sumsGoingUp.length && k === totalLength) {
        for (var i = 0; i < arr.length; i++) {
            var temp = sumsGoingUp[i] + sumsGoingDown[i]
            if (temp <= res || !res) {
                res = temp
            } else {
                break
            }
        }
    }
    //
    // console.log(leftBest)
    // console.log(rightBest)

    return Math.min(leftBest, rightBest, res)
}

// const arr15 = [1,1,2,3, 4, 4, 5]
// console.log(solve(arr15, 6))
// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// const arr10 = [1, 2, 3, 4, 5, 6]
// console.log(solve(arr10, 6))
//
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)
//
// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10) === 42)
//
// const arr8 = [1, 123]
// console.log(solve(arr8, 2) === 122)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    if(x === 921851939) {
        print(nums.slice(0, 12), nums.slice(-12))
    }

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }
    var valuesLeft = values.map(x => Object.assign({}, x))
    var valuesRight = values.map(x => Object.assign({}, x))
    var valuesAll = values.map(x => Object.assign({}, x))

    var resFromLeft = checkFromLeft(valuesLeft, k)
    var resFromRight = checkFromRight(valuesRight, k)
    var res = checkAll(valuesAll, k)

    // console.log('left', resFromLeft)
    // console.log('right', resFromRight)
    return Math.min(resFromLeft, resFromRight, res)
}

function checkFromLeft(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = 0; i < arr.length - 1; i++) {
        var diff = arr[i + 1].value - arr[i].value

        if (arr[i].count >= k) return cost

        if (l - i === 2) {
            return cost + (k - Math.min(arr[i].count, arr[i + 1].count)) * diff
        } else {
            arr[i + 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkFromRight(arr, k) {
    var cost = 0
    var l = arr.length
    for (var i = l - 1; i > 0; i--) {
        var diff = arr[i].value - arr[i - 1].value

        if (arr[i].count >= k) return cost

        if (i === 1) {
            return cost + (k - Math.max(arr[i].count, arr[i - 1].count)) * diff
        } else {
            arr[i - 1].count += arr[i].count
            cost += diff * arr[i].count
        }
    }
}

function checkAll(arr, k) {
    var sumsGoingUp = [0]
    var sumsGoingDown = [0]
    var cost = 0
    var count = arr[0].count

    arr.forEach((n, index) => {
        if (index < arr.length - 1) {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index + 1] = cost
        }
    })

    count = arr[arr.length - 1].count
    cost = 0

    arr
        .slice()
        .reverse()
        .forEach((n, index, arr) => {
            if (index < arr.length - 1) {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index + 1] = cost
            }
        })

    sumsGoingDown.reverse()

    var res

    for (var i = 0; i < arr.length; i++) {
        var temp = sumsGoingUp[i] + sumsGoingDown[i]
        if (temp <= res || !res) {
            res = temp
        } else {
            break
        }
    }
    //
    // console.log(sumsGoingUp)
    // console.log(sumsGoingDown)

    return res
}

// const arr = [1, 2, 3, 3, 3]
// console.log()

// const arr = [1, 4, 4, 5, 10, 12, 12, 12]
// console.log(solve(arr, 6))

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// // const arr10 = [1, 2, 3, 4, 5, 6]
// // console.log(solve(arr10, 6))
// //
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)

// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10))

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    nums.sort(function (a, b) {
        return a - b
    })

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }

    return checkAll(values, k, nums.length)
}

function checkAll(arr, k, totalLength) {
    var sumsGoingUp = []
    var sumsGoingDown = []
    var cost = 0
    var count = arr[0].count
    var leftBest, rightBest

    for (var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index + 1].value - arr[index].value
        if (arr[index + 1].count + count >= k) {
            var overflow = arr[index + 1].count + count - k
            if(index === arr.length - 2) {
                leftBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                break
            } else {
                leftBest = cost + (count - overflow) * diff
                break
            }
        } else {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index] = cost
        }
    }

    count = arr[arr.length - 1].count
    cost = 0

    arr.reverse()

    for(var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index].value - arr[index + 1].value
            if(arr[index + 1].count + count >= k) {
                var overflow = arr[index + 1].count + count - k
                if(index === arr.length - 2) {
                    rightBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                    break
                } else {
                    rightBest = cost + (count - overflow) * diff
                    break
                }
            } else {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index] = cost
            }
    }

    sumsGoingDown.reverse()

    var res = Number.MAX_SAFE_INTEGER

    if(sumsGoingDown.length && sumsGoingUp.length && k === totalLength) {
        for (var i = 0; i < arr.length; i++) {
            var temp = sumsGoingUp[i] + sumsGoingDown[i]
            if (temp <= res || !res) {
                res = temp
            } else {
                break
            }
        }
    }

    return Math.min(leftBest, rightBest, res)
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// const arr10 = [1, 2, 3, 4, 5, 6]
// console.log(solve(arr10, 6))
//
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)
//
// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10) === 42)
//
// const arr8 = [1, 123]
// console.log(solve(arr8, 2) === 122)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))

function solve(nums, k) {
    if (k === 0) return 0

    var x = nums[0]

    nums.sort(function (a, b) {
        return a - b
    })

    if(x === 561987393) {
        print(nums.slice(10), nums.slice(-10))
    }

    var distance = findDistance(nums.slice(), k)
    return distance
}

function findDistance(nums, k) {
    var values = []
    var index = 0
    var l = nums.length
    while (index < nums.length) {
        var count = 0
        var currentValue = nums[index]
        while (currentValue === nums[index] && nums.length) {
            ++count
            if (count === k) {
                return 0
            }
            index++
        }
        values.push({
            count: count,
            value: currentValue
        })
        currentValue = nums[index]
    }

    return checkAll(values, k, nums.length)
}

function checkAll(arr, k, totalLength) {
    var sumsGoingUp = []
    var sumsGoingDown = []
    var cost = 0
    var count = arr[0].count
    var leftBest, rightBest

    for (var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index + 1].value - arr[index].value
        if (arr[index + 1].count + count >= k) {
            var overflow = arr[index + 1].count + count - k
            if(index === arr.length - 2) {
                leftBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                break
            } else {
                leftBest = cost + (count - overflow) * diff
                break
            }
        } else {
            cost += (arr[index + 1].value - arr[index].value) * count
            count += arr[index + 1].count
            sumsGoingUp[index] = cost
        }
    }

    count = arr[arr.length - 1].count
    cost = 0

    arr.reverse()

    for(var index = 0; index < arr.length - 1; index++) {
        var diff = arr[index].value - arr[index + 1].value
            if(arr[index + 1].count + count >= k) {
                var overflow = arr[index + 1].count + count - k
                if(index === arr.length - 2) {
                    rightBest = cost + (Math.min(count, arr[index + 1].count) - overflow) * diff
                    break
                } else {
                    rightBest = cost + (count - overflow) * diff
                    break
                }
            } else {
                cost += (arr[index].value - arr[index + 1].value) * count
                count += arr[index + 1].count
                sumsGoingDown[index] = cost
            }
    }

    sumsGoingDown.reverse()

    var res = Number.MAX_SAFE_INTEGER

    if(sumsGoingDown.length && sumsGoingUp.length && k === totalLength) {
        for (var i = 0; i < arr.length; i++) {
            var temp = sumsGoingUp[i] + sumsGoingDown[i]
            if (temp <= res || !res) {
                res = temp
            } else {
                break
            }
        }
    }

    return Math.min(leftBest, rightBest, res)
}

// const arr1 = [1, 2, 3, 4, 5]
// console.log(solve(arr1, 5) === 6)
// const arr10 = [1, 2, 3, 4, 5, 6]
// console.log(solve(arr10, 6))
//
// const arr2 = [1, 1, 1, 2, 5]
// console.log(solve(arr2, 4) === 3)
// // // //
// const arr32 = [1, 1, 1, 2, 2]
// console.log(solve(arr32, 3) === 0)
// //
// // //
//
// const arr4 = Array.from({length: 200000}, (_, index) => ++index)
// console.log(solve(arr4, 200000) === 10000000000)
// // // //
// const arr5 = [1, 2, 2, 4, 2, 3]
// console.log(solve(arr5, 5) === 3)
// // // //
// const arr6 = [1, 1, 1, 2, 3, 3, 3]
// console.log(solve(arr6, 5) === 4)
//
// const arr = [1285, 1286, 1288, 1288, 1289, 1290, 1292, 1292, 1293, 1294, 1294, 1296, 2000, 2273, 2275, 2275, 2277, 2278, 2278, 2278, 2280, 2280, 2285]
// console.log(solve(arr, 10) === 42)
//
// const arr8 = [1, 123]
// console.log(solve(arr8, 2) === 122)

var line1 = readline().split(" ")
var k = Number(line1[1])
var nums = readline().split(" ").map(function(x) {return Number(x)})
print(solve(nums, k))


You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

var a = [];
var b = [];

var n, m = readline();
a = readline().split(' ').map((x) => Number(x));
b = readline().split(' ').map((x) => Number(x));
a.sort((a, b) => a - b);

function check(target, mid) {
    return a[mid] <= target;
}

function bs(a, target) {
  var low = 0;
  var high = a.length - 1;
  var ans = -1;

  while(low <= high) {
    var mid = Math.floor((low + high) / 2);
    if (!check(target, mid)) {
      high = mid - 1;
    } else {
      low = mid + 1;
      ans = mid;
    }
  }

  return ans + 1;
}

b.forEach(function(el) {
    write(bs(a, el) + " ") ;
});

readline(); // Ignore.
var a = readline().split(" ").map(i => +i);
var b = readline().split(" ").map(i => +i);
a.sort((i,j) => i - j);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = ((sectorEnd + sectorStart) / 2) << 0;
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
write(b.map((bi) => countLessOrEqual(bi, a)).join(" ") + "\n");

readline();
var a = readline().split(" ").map(i => parseInt(i, 10));
var b = readline().split(" ").map(i => parseInt(i, 10));
a.sort((i,j) => i - j);
var aLength = a.length;
var countLessOrEqual = (bi) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[aLength-1] <= bi) {
        return aLength;
    }
    var sectorStart = 0;
    var sectorEnd = aLength - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map(countLessOrEqual).join(" "));

var input = readline().split(' ').map(i => parseInt(i));
var n = input[0];
var m = input[1];
var a = readline().split(" ").map(i => parseInt(i));
var b = readline().split(" ").map(i => parseInt(i));
a.sort((i,j) => i - j);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map((bi) => countLessOrEqual(bi, a)).join(" "));

readline();
var a = readline().split(" ").map(i => parseInt(i, 10));
var b = readline().split(" ").map(i => parseInt(i, 10));
a.sort((i,j) => i - j);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
write(b.map((bi) => countLessOrEqual(bi, a)).join(" ") + "\n");

var a = [1,3,5,7,9];
var b = [6,4,2,8];

function check(target, mid) {
    return a[mid] <= target;
}

function bs(a, target) {
  var low = 0;
  var high = a.length - 1;
  var ans = -1;

  while(low <= high) {
    var mid = Math.floor((low + high) / 2);
    if (!check(target, mid)) {
      high = mid - 1;
    } else {
      low = mid + 1;
      ans = mid;
    }
  }

  return ans + 1;
}

b.forEach(function(el) {
    write(bs(a, el) + " ") ;
});

var n, m = readline();

a = readline().split(' ');
b = readline().split(' ');

a.sort((a, b) => a < b);

var input = readline().split(' ').map(i => parseInt(i));
var n = input[0];
var m = input[1];
var a = readline().split(" ").map(i => parseInt(i));
var b = readline().split(" ").map(i => parseInt(i));
a.sort((i,j) => i - j);
print(a);
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map((bi) => countLessOrEqual(bi, a)).join(" "));

var input = readline().split(' ').map(i => parseInt(i));
var n = input[0];
var m = input[1];
var a = readline().split(" ").map(i => parseInt(i));
var b = readline().split(" ").map(i => parseInt(i));
a.sort();
var countLessOrEqual = (bi, a) => {
    if (a[0] > bi) {
        return 0;
    } else if (a[a.length-1] <= bi) {
        return a.length;
    }
    var sectorStart = 0;
    var sectorEnd = a.length - 1;
    while (sectorStart <= sectorEnd)
    {
        middle = Math.floor((sectorEnd + sectorStart) / 2);
        if (a[middle] > bi && (middle === 0 || a[middle-1] <= bi)) {
           return middle;
        } else if (a[middle] > bi) {
           sectorEnd = middle - 1;
        } else {
           sectorStart = middle + 1;
        }
    }
};
print(b.map((bi) => countLessOrEqual(bi, a)).join(" "));


Vasya has a string $$$s$$$ of length $$$n$$$. He decides to make the following modification to the string:   Pick an integer $$$k$$$, ($$$1 \leq k \leq n$$$).  For $$$i$$$ from $$$1$$$ to $$$n-k+1$$$, reverse the substring $$$s[i:i+k-1]$$$ of $$$s$$$. For example, if string $$$s$$$ is qwer and $$$k = 2$$$, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length $$$2$$$)  weqr (after reversing the second substring of length $$$2$$$)  werq (after reversing the last substring of length $$$2$$$)  Hence, the resulting string after modifying $$$s$$$ with $$$k = 2$$$ is werq. Vasya wants to choose a $$$k$$$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $$$k$$$. Among all such $$$k$$$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of $$$n$$$ lowercase latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.

For each testcase output two lines: In the first line output the lexicographically smallest string $$$s'$$$ achievable after the above-mentioned modification.  In the second line output the appropriate value of $$$k$$$ ($$$1 \leq k \leq n$$$) that you chose for performing the modification. If there are multiple values of $$$k$$$ that give the lexicographically smallest string, output the smallest value of $$$k$$$ among them.

6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p

abab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1

NoteIn the first testcase of the first sample, the string modification results for the sample abab are as follows :   for $$$k = 1$$$ : abab  for $$$k = 2$$$ : baba  for $$$k = 3$$$ : abab  for $$$k = 4$$$ : babaThe lexicographically smallest string achievable through modification is abab for $$$k = 1$$$ and $$$3$$$. Smallest value of $$$k$$$ needed to achieve is hence $$$1$$$.

process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  while(t--) {
    const n = readInt(input, ptr++)
    let s = input[ptr++]
    let sMin = s
    let kMin = 1
    for(let k = 0; k < n; k ++) {
      let x = s.substr(k + 1)
      if(n % 2 === (k + 1) % 2) {
        x = x + s.substr(0, k + 1)
      }
      else x += s.substr(0, k + 1).split('').reverse().join('')
      // console.log(x, k + 2)
      if(x < sMin) {
        sMin = x
        kMin = k + 2
      }
    }
    wr(sMin)
    wr(kMin)
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
function getIndex(n, k, i){
  if (i > n - k){
    return (n + k) % 2 !== 0 ? i - (n - k + 1) : n - i - 1;
  }
  return k - 1 + i;
}

function solution(n, st) {
  let k = 1;
  for(let j = 2; j <= n; j++){
    for (let i = 0; i < n; i++){
      let c1 = st[getIndex(n, k, i)];
      let c2 = st[getIndex(n, j, i)];

      //console.log(k, j, i, c1, c2);
      if (c2 < c1) {
        k = j;
      }
      if (c2 !== c1) break;
    }
  }

  let min = '';
  for (let i = 0; i < n; i++){
    min += st[getIndex(n, k, i)];
  }

  return [min, k];
}

function main() {
    const N = parseInt(readline());

    for(let i = 0; i < N; i++){
        const line1 = readline().split(' ').map(item => parseInt(item));
        const line2 = readline();
        const res = solution(line1[0], line2);
        console.log(res[0]);
        console.log(res[1]);
    }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let s=0;s<t;++s){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const s=n(r(747));let i="",o=[],u=0,l="";const a="local"===process.argv[2],p=t=>{if(a){if(o=s.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),s.default.writeFileSync("output.txt",l),console.log(l),s.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{i+=t})),process.stdin.on("end",(e=>{o=i.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function h(){return o[u++]}function f(){return h().split(" ").map((t=>parseFloat(t)))}function c(){return h().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:h,nextNumbers:f,nextBigNumbers:function(){return h().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const s=n(r(312));s.default.runEachTest((function(){let[t]=s.default.nextNumbers(),e=s.default.readline(),r=[];if(1==t)return s.default.puts(e),void s.default.puts(1);for(let n=0;n<t;++n){let s=e.substr(n,e.length),i=e.substr(0,n);t%2!=n%2&&(i=i.split("").reverse().join(""));let o=s+i;r.push({val:o,ndx:n})}let n=r.sort(((t,e)=>{let r=t.val.localeCompare(e.val);return 0==r?t.ndx-e.ndx:r}))[0];s.default.puts(n.val),s.default.puts(n.ndx+1)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var s=e[n]={exports:{}};return t[n].call(s.exports,s,s.exports,r),s.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let s = io.readline()
//
//   let candidates = []
//
//   if (n == 1) {
//     io.puts(s)
//     io.puts(1)
//     return
//   }
//
//   for (let i = 0; i < n; ++i) {
//     let v = s.substr(i, s.length)
//     let p = s.substr(0, i)
//     if (n % 2 != i % 2) {
//       p = p.split("").reverse().join("")
//     }
//
//     let c = v + p
//
//     candidates.push({ val: c, ndx: i })
//   }
//
//   // io.debug(candidates)
//
//   let f = candidates.sort((x, y) => {
//     let c = x.val.localeCompare(y.val)
//
//     if (c == 0) {
//       return x.ndx - y.ndx
//     }
//
//     return c
//   })[0]
//
//   io.puts(f.val)
//   io.puts(f.ndx + 1)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

'use strict'

const problem = (n, s) => {
    const a = [];
    const r = s.split('').reverse().join('');
    for (let i = 0; i < n; i++) {
        if (n%2 === i%2) a.push(s.slice(i) + s.slice(0, i))
        else a.push(s.slice(i) + r.slice(n - i))
    }
    let x = a[0], j = 0;

    for (let i = 1; i < n; i++) if (a[i] < x) x = a[j = i];

    return `${x}\n${j+1}`;
}

let t = +readline()
while(t--) print(problem(+readline(), readline()))


Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!To compose a story, Stephen wrote out $$$n$$$ words consisting of the first $$$5$$$ lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs $$$5$$$ times, all other letters occur $$$4$$$ times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total).You are given a sequence of $$$n$$$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $$$0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of the words in the sequence. Then $$$n$$$ lines follow, each of them contains a word — a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i. e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$; the sum of the lengths of all words over all test cases doesn't exceed $$$4 \cdot 10^5$$$.

For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story.

6
3
bac
aaada
e
3
aba
abcde
aba
2
baba
baba
4
ab
ab
c
bc
5
cbdca
d
a
d
e
3
b
c
ca

NoteIn the first test case of the example, all $$$3$$$ words can be used to make an interesting story. The interesting story is "bac aaada e".In the second test case of the example, the $$$1$$$-st and the $$$3$$$-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time.In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is $$$0$$$.In the fourth test case of the example, Stephen can use the $$$3$$$-rd and the $$$4$$$-th words to make an interesting story. The interesting story is "c bc".

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function freq (s, c) {
	let cnt = 0;
	for (const ltr of s) {
		cnt += ltr == c;
	}
	return cnt;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = [];
		for (let i = 0; i < n; i++) {
			s[i] = rl();
		}

		let ans = 0;
		for (const c of ['a', 'b', 'c', 'd', 'e']) {
			const need = [];
			let extras = 0, cnt = 0;
			for (const w of s) {
				const extra = 2 * freq(w, c) - w.length;
				if (extra >= 0) {
					extras += extra;
					cnt++;
				} else {
					need.push(-extra);
				}
			}

			if (extras == 0){
				continue;
			}

			need.sort((x, y) => x - y);
			for (const x of need) {
				extras -= x;
				cnt += extras > 0;
			}

			ans = Math.max(ans, cnt);
		}

		console.log(ans);
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function freq (s, c) {
	let cnt = 0;
	for (const ltr of s) {
		cnt += ltr == c;
	}
	return cnt;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = [];
		for (let i = 0; i < n; i++) {
			s[i] = rl();
		}

		const ltrs = ['a', 'b', 'c', 'd', 'e'];
		let ans = 0;
		for (const ltr of ltrs) {
			const frq = [];
			let extras = 0;
			let cnt = 0;
			for (let i = 0; i < n; i++) {
				const avl = 2 * freq(s[i], ltr) - s[i].length;
				if (avl >= 0) {
					extras += avl;
					cnt++;
				} else {
					frq.push(-avl);
				}
			}

			frq.sort((x, y) => x - y);
			let i = 0;
			if (extras == 0) continue;
			while (i < frq.length && extras - frq[i] > 0 ) {
				cnt++;
				extras -= frq[i++];
			}
			//console.log({cnt})

			ans = Math.max(ans, cnt);
		}

		console.log(ans);
	}
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines.slice(l, l + n).map(s => s.trim())
        l += n
        console.log(solve(n, arr))
    }
});

function solve(n, arr) {
    const count = arr.map(str => {
        const map = [0,0,0,0,0,0]
        for (let i = 0; i < str.length; i++) {
            const idx = str.charCodeAt(i) - 'a'.charCodeAt(0)
            map[idx]++
            map[5]++ // total
        }
        return map
    })
// console.log(count)
    let max = 0
    ;[0,1,2,3,4].map(i => {
        count.sort((a, b) => (a[5] - a[i] * 2) - (b[5] - b[i] * 2))
        // console.log(i, count)
        let a = 0
        let b = 0
        count.some((map, j) => {
            a += map[i]
            b += map[5]
            if (a <= b / 2) return true
            // console.log(i, j + 1)
            max = Math.max(max, j + 1)
        })
    })
    return max
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);

const n = readNum();

for(var i = 0; i < n; i++) {
  var m = readNum();
  var bc = 0;
  var strs = [];
  var l = new Set();

  for(var j = 0; j < m; j++) {
    strs[j] = readStr();
    for(var k = 0; k < strs[j].length; k++) {
      l.add(strs[j][k]);
    }
  }

  for (var item of l) {
    var a = 0, b = 0, ans = [];
    for(var j = 0; j < m; j++) {
      var la = 0, lb = 0;
      for(var k = 0; k < strs[j].length; k++) {
        if(strs[j][k] === item) {
          la++;
        }
      }
      lb = strs[j].length - la;
      ans.push([la, lb, lb - la]);
      a += la;
      b += lb;
    }
    if(a > b) {
      bc = m;
      break;
    }
    ans.sort((a, b) => a[2] - b[2]);
    var t = m;
    while(t && t > bc) {
      t--;
      a -= ans[t][0];
      b -= ans[t][1];
      if(a > b) {
        bc = t;
        break;
      }
    }
  }

  print(bc);
}


This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions:   The length of $$$t$$$ does not exceed the length of $$$s$$$.  $$$t$$$ is a palindrome.  There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$10^6$$$.

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$.  It is a palindrome.  "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".