본문으로 바로가기

백준 15654 - N과 M (5)

category BOJ 백준/기타 2020. 11. 16. 17:16

출처 : https://www.acmicpc.net/problem/15654 

 

15654번: N과 M (5)

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

www.acmicpc.net

 

고려사항

  • next_permutation 을 활용하여 수열 구하기.
  • 첫 next_permutation 반복문에서는 뽑을 수들을 정하고, 이들을 벡터에 담아 수열들을 구하여
    정답 벡터에 삽입.
  • 정렬하여 출력.

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool cmp(int a, int b){
    return a > b;
}

int main() {
    vector<int> v;
    vector<int> num;
    vector<vector<int>> ans;
    int n, m, tmp;
    cin>>n>>m;

    for(int i=0;i<n;++i){
        cin>>tmp;
        num.push_back(tmp);
        if(i < n-m){
            v.push_back(0);
        }else{
            v.push_back(1);
        }
    }
    sort(num.begin(), num.end(), cmp);

    do{
        vector<int> tmp;
        for(int i=n-1;i>=0;--i){
            if(v[i]){
                tmp.push_back(num[i]);
            }
        }
        do{
            ans.push_back(tmp);
        }while(next_permutation(tmp.begin(), tmp.end()));
    }while(next_permutation(v.begin(), v.end()));

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

    return 0;
}