[백준/C++] 로또

2 분 소요

로또

n the German Lotto you have to select 6 numbers from the set {1,2,…,49}. A popular strategy to play Lotto - although it doesn’t increase your chance of winning - is to select a subset S containing k (k>6) of these 49 numbers, and then play several games with choosing numbers only from S. For example, for k=8 and S = {1,2,3,5,8,13,21,34} there are 28 possible games: [1,2,3,5,8,13], [1,2,3,5,8,21], [1,2,3,5,8,34], [1,2,3,5,13,21], … [3,5,8,13,21,34].

Your job is to write a program that reads in the number k and the set S and then prints all possible games choosing numbers only from S.

입력 The input file will contain one or more test cases. Each test case consists of one line containing several integers separated from each other by spaces. The first integer on the line will be the number k (6 < k < 13). Then k integers, specifying the set S, will follow in ascending order. Input will be terminated by a value of zero (0) for k.

출력 For each test case, print all possible games, each game on one line. The numbers of each game have to be sorted in ascending order and separated from each other by exactly one space. The games themselves have to be sorted lexicographically, that means sorted by the lowest number first, then by the second lowest and so on, as demonstrated in the sample output below. The test cases have to be separated from each other by exactly one blank line. Do not put a blank line after the last test case.

# 풀이

순열 문제라고 해서 일단 순열을 구하는 함수를 재귀로 구현해 보았다. 기저 조건은 6개의 수를 택했을 때이고 완전탐색을 하며 6개를 뽑는 모든 경우를 찾는다. 첫 번째 for 루프말인데, 이 문제를 좀 예전에 풀어서 저번 스터디에서 민규가 N과 M문제를 풀며 보여주었던 방식이 들어가있지 않다. 지금 코드를 짠다고 하면 저렇게 인덱스를 구하지 말고 재귀함수의 인자로 인덱스 값을 넘겨주는 식으로 할 것이다.

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

int k;
bool visit[13] = {false};
vector<int> v;
int S[49];

void permutation(int cnt)
{
	if(cnt == 6) {
		for(int i = 0; i < 6; ++i)
			cout << v[i] << ' ';
			cout << "\n";
			return;
	}

	int index;
	for(index = k; index > 0; --index)
		if(visit[index]) break;

	for(int i = index; i < k; ++i) {
		if(visit[i]) continue;
		visit[i] = true;
		v.push_back(S[i]);
		permutation(cnt + 1);
		visit[i] = false;
		v.pop_back();
	}
}

int main()
{
	//ios::sync_with_stdio(false);
	//cin.tie(NULL);

	while(1) {
		cin >> k;
		if(k == 0) break;
	
		for(int i = 0; i < k; ++i)
			cin >> S[i];

		permutation(0);
		cout << "\n";
	}

	return 0;
}

index를 매개변수로 넘겨주고 pop_back과정을 for문에 자연스럽게 담은 버전의 코드가 다음과 같다.

#include <iostream>
#define MAX 13
using namespace std;

int S[MAX];
int combination[MAX];
int k;

void dfs(int start, int depth)
{
	if(depth == 6) {
		for(int i = 0; i < 6; ++i)
			cout << combination[i] << ' ';
		cout << "\n";
		return;
	}

	for(int i = start; i < k; ++i) {
		combination[depth] = S[i];
		dfs(i + 1, depth + 1);
	}
}

int main()
{
	while(cin >> k && k) {
		for(int i = 0; i < k; ++i)
			cin >> S[i];
		
		dfs(0,0);
		cout << "\n";
	}

	return 0;
}

댓글남기기