[백준] 15664번

Jeanine·2022년 3월 31일
0

baekjoon

목록 보기
55/120
post-thumbnail

💻 C++ 기반

N과 M (10)
https://www.acmicpc.net/problem/15664

1. 백트래킹 코드

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

#define MAX 9

using namespace std;

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

void func(int K, int idx)
{
    if (K == M)
    {
        for (int i = 0; i < M; i++)
        {
            printf("%d ", output[i]);
        }
        printf("\n");
        return;
    }
    int prev = 0;
    for (int i = idx; i < N; i++)
    {
        if (!isUsed[i] && prev != input[i])
        {
            isUsed[i] = true;
            output[K] = input[i];
            prev = input[i];
            func(K + 1, i);
            isUsed[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>

#define MAX 9

using namespace std;

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

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
    {
        vector<int> temp;
        for (int i = 0; i < N; i++)
        {
            if (!arr[i])
            {
                temp.push_back(input[i]);
            }
        }
        output.push_back(temp);
    } while (next_permutation(arr.begin(), arr.end()));

    sort(output.begin(), output.end());
    output.erase(unique(output.begin(), output.end()), output.end());
    
    for (int i = 0; i < output.size(); i++)
    {
        for (int j = 0; j < output[i].size(); j++)
        {
            printf("%d ", output[i][j]);
        }
        printf("\n");
    }

    return 0;
}
profile
Grow up everyday

0개의 댓글