프로그래밍/알고리즘

BOJ 15654 · N과 M (5)

반응형


알고리즘 분류 : 브루트 포스  


N개의 숫자를 입력받고, 그 숫자 중에서 M개를 뽑아서 출력하는 문제다. N과 M (1)의 소스코드를 살짝 수정하면 된다. N과 M (1)에서는 1~N까지의 숫자를 사용했으니, 이번에는 배열에 있는 N개의 숫자를 사용하면 된다.




C++ 소스코드


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

int n, m;
int a[8];
bool check[8];
vector<int> v;

void solve(int cnt) {
    if (cnt == m) {
        for (auto k : v) printf("%d ", k);
        printf("\n");
        return;
    }
    for (int i=0; i<n; i++) {
        if (!check[i]) {
            check[i] = true;
            v.push_back(a[i]);
            solve(cnt+1);
            v.pop_back();
            check[i] = false;
        }
    }
}

int main() {
    scanf("%d %d", &n, &m);
    for (int i=0; i<n; i++) scanf("%d", &a[i]);
    sort(a, a+n);
    solve(0);
    return 0;
}




Python 3 소스코드


from sys import stdin, stdout
input = stdin.readline
print = stdout.write

n, m = map(int, input().split())
a = sorted(list(map(int, input().split())))
check = [False]*n
v = []

def solve(cnt):
    if cnt == m:
        print(' '.join(map(str, v))+'\n')
        return
    for i in range(n):
        if not check[i]:
            check[i] = True
            v.append(a[i])
            solve(cnt+1)
            v.pop()
            check[i] = False

solve(0)


✓ 이번 문제도 순열 (Permutation)로 구현할 수 있다.

✓ 파이썬은 itertools에 있는 permutations를 이용하면 편하다.


from sys import stdin, stdout
from itertools import permutations
input = stdin.readline
print = stdout.write

n, m = map(int, input().split())
for k in permutations(sorted(list(map(int, input().split()))), m):
    print(' '.join(map(str, k))+'\n')




참고



반응형