[백준] 15655번

Jeanine·2022년 3월 30일
0

baekjoon

목록 보기
51/120
post-thumbnail
post-custom-banner

💻 C++ 기반

N과 M (6)
https://www.acmicpc.net/problem/15655

1. 백트래킹 코드

#include <cstdio>
#include <vector>
#include <algorithm>

#define MAX 9
#define MAX_NUM 10001

using namespace std;

int N, M;
vector<int> input;
int isUsed[MAX_NUM];
int output[MAX];

void func(int K, int idx)
{
    if (K == M)
    {
        for (int i = 0; i < M; i++)
        {
            printf("%d ", output[i]);
        }
        printf("\n");
        return;
    }
    for (int i = idx; i < N; i++)
    {
        if (!isUsed[input[i]])
        {
            isUsed[input[i]] = true;
            output[K] = input[i];
            func(K + 1, i);
            isUsed[input[i]] = false;
        }
    }
}

int main()
{
    scanf("%d %d", &N, &M);
    for (int i = 0; i < N; i++)
    {
        int num;
        scanf("%d", &num);
        input.push_back(num);
    }
    sort(input.begin(), input.end());

    func(0, 0);

    return 0;
}

2. next_permutation 코드

#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

int N, M;
vector<int> input;
vector<int> arr;

int main()
{
    scanf("%d %d", &N, &M);
    for (int i = 0; i < N; i++)
    {
        int num;
        scanf("%d", &num);
        input.push_back(num);
    }
    sort(input.begin(), input.end());
    
    for (int i = 0; i < M; i++)
    {
        arr.push_back(0);
    }
    for (int i = M; i < N; i++)
    {
        arr.push_back(1);
    }

    do
    {
        for (int i = 0; i < N; i++)
        {
            if (arr[i] == 0)
            {
                printf("%d ", input[i]);
            }
        }
        printf("\n");
    } while (next_permutation(arr.begin(), arr.end()));

    return 0;
}
profile
Grow up everyday
post-custom-banner

0개의 댓글