BOJ/백트래킹

15654번: N과 M (5) (BOJ C/C++)

둠치킨 2022. 9. 2. 15:55

15654번: N과 M (5)

사용 언어: C++

 

문제

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

  • N개의 자연수 중에서 M개를 고른 수열

입력

첫째 줄에 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)

둘째 줄에 N개의 수가 주어진다. 입력으로 주어지는 수는 10,000보다 작거나 같은 자연수이다.

출력

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.

수열은 사전 순으로 증가하는 순서로 출력해야 한다.

 

풀이 1

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

int n, m;
int arr[10];
int num[10];
bool isused[10];

void func(int cur){
    if(cur == m){
        for(int i=0; i<m; i++)
            cout << num[arr[i]] << ' ';
        cout << '\n';
        return;
    }
    //오름차순 출력이 아니기 때문에 i=0에서 시작
    for(int i=0; i<n; i++){
        if(!isused[i]){
            arr[cur] = i;
            isused[i] = 1;
            func(cur+1);
            isused[i] = 0;
        }
    }
}

int main(void){
    ios::sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> m;
    for(int i=0; i<n; i++) cin >> num[i];

    sort(num, num+n);
    func(0);

    return 0;
}

 

풀이 2

next_permutation을 사용할 수 있지만, 2중으로 써야해서 풀이 1에 비해 메모리와 시간을 더 잡아 먹는 풀이다.

  1. 첫 번째 next_permutation : arr에 저장한 0과 1들을 갖고 돌리는 next_permutation (조합)
  2. 두 번쨰 next_permutation : 조합으로 뽑은 숫자들을 갖고 next_permutation을 돌려서 수열 구함
  3. tmp(수열)을 ans에 저장 후 정렬
#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<int> arr;
vector<int> num;
vector<vector<int>> ans;

int main(void){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m, tmp;
    cin >> n >> m;
    for(int i=0; i<n; i++){
        cin >> tmp;
        num.push_back(tmp);
    }
    sort(num.begin(), num.end());
    for(int i=0; i<n; ++i)  arr.push_back(i < m ? 0 : 1);
    do{
        vector<int> tmp;
        for(int i=0; i<n; i++)
            if(!arr[i]) tmp.push_back(num[i]); //arr의 0과 1로 조합 -> tmp에 저장
        do{
            ans.push_back(tmp); //tmp에 대한 next_permutation 시행
        }while(next_permutation(tmp.begin(), tmp.end()));
    }while(next_permutation(arr.begin(), arr.end()));

    //
    sort(ans.begin(), ans.end()); //정렬
    for(auto i : ans){
        for(auto j : i)
            cout << j << ' ';
        cout << '\n';
    }

    return 0;
}