import Foundation func isolateAnimals(_ animals: [String], types: (String, String), _ s: [Int], _ d: [Int]) -> [Int] { var indices = [Int]() for index in 0 ..< animals.count { if animals[index] == types.0 || animals[index] == types.1 { if d[index] > s[index] { indices.append(index) } } } return indices } func quicksort(_ a: [T]) -> [T] { guard a.count > 1 else { return a } let pivot = a[a.count/2] let less = a.filter { $0 < pivot } let equal = a.filter { $0 == pivot } let greater = a.filter { $0 > pivot } return quicksort(less) + equal + quicksort(greater) } func tryCombinations(_ x: Int, of indices: [Int], in destinations: [Int]) -> Int? { var validDestinations = [Int]() for index in indices { validDestinations.append(destinations[index]) } validDestinations = quicksort(validDestinations) guard validDestinations.count > x - 1 else { return nil } return validDestinations[x - 1] } for _ in 1 ... Int(readLine()!)! { // m = number of zoos, n = number of animals let MN = readLine()!.split(separator: " ").map { Int($0)! } let animals = readLine()!.split(separator: " ").map { "\($0)" } let sourceZoos = readLine()!.split(separator: " ").map { Int($0)! } let destinations = readLine()!.split(separator: " ").map { Int($0)! } let indicesOfEC = isolateAnimals(animals, types: ("E", "C"), sourceZoos, destinations) let indicesOfDM = isolateAnimals(animals, types: ("D", "M"), sourceZoos, destinations) var outputLine = "" for x in 1 ... MN[1] { if indicesOfEC.count < x && indicesOfDM.count < x { outputLine += "-1 " } else { let minEC = tryCombinations(x, of: indicesOfEC, in: destinations) let minDM = tryCombinations(x, of: indicesOfDM, in: destinations) if minEC == nil && minDM == nil { outputLine += "-1 " } else if minEC == nil { outputLine += "\(minDM!) " } else if minDM == nil { outputLine += "\(minEC!) " } else { if minEC! < minDM! { outputLine += "\(minEC!) " } else { outputLine += "\(minDM!) " } } } } print(outputLine.dropLast()) }