https://www.acmicpc.net/problem/15657

 

15657번: N과 M (8)

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열

www.acmicpc.net

 

[난이도] Silver3
[유형] 백트래킹

[풀이]
수열이 오름차순이어야 하므로 배열을 정렬해주고
백트래킹을 해주면 됩니다.

 

import java.util.*
val bw = System.`out`.bufferedWriter()
var N=0
var M=0
lateinit var arr:List<Int>
fun sol(n:Int,s:String){
    if(s.filter { it==' ' }.length==M){
        bw.write(s.trim()+'\n')
        return
    }
        for(i in n until N){
        sol(i, "$s ${arr[i]}")
    }
}
fun main() = with(System.`in`.bufferedReader()){
    val ip = readLine().split(' ').map { it.toInt() }
    N=ip[0]
    M=ip[1]
    arr = readLine().split(' ').map{it.toInt()}
    arr = arr.sortedWith{a,b-> a.compareTo(b)}
    sol(0,"")
    bw.close()
}


https://github.com/has2/Problem-Solving/blob/master/boj-solved.ac/Silver3/15657.cpp

+ Recent posts