[6603] 로또

Update:     Updated:

카테고리:

태그:

[Silver II] 로또 - 6603

문제 링크

성능 요약

메모리: 19368 KB, 시간: 236 ms

분류

수학, 조합론, 백트래킹, 재귀

문제 설명

독일 로또는 {1, 2, ..., 49}에서 수 6개를 고른다.

로또 번호를 선택하는데 사용되는 가장 유명한 전략은 49가지 수 중 k(k>6)개의 수를 골라 집합 S를 만든 다음 그 수만 가지고 번호를 선택하는 것이다.

예를 들어, k=8, S={1,2,3,5,8,13,21,34}인 경우 이 집합 S에서 수를 고를 수 있는 경우의 수는 총 28가지이다. ([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])

집합 S와 k가 주어졌을 때, 수를 고르는 모든 방법을 구하는 프로그램을 작성하시오.

입력

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있다. 첫 번째 수는 k (6 < k < 13)이고, 다음 k개 수는 집합 S에 포함되는 수이다. S의 원소는 오름차순으로 주어진다.

입력의 마지막 줄에는 0이 하나 주어진다.

출력

각 테스트 케이스마다 수를 고르는 모든 방법을 출력한다. 이때, 사전 순으로 출력한다.

각 테스트 케이스 사이에는 빈 줄을 하나 출력한다.

아이디어

조합만 알면 간단하게 풀 수 있는 문제이다.

답안코드

import java.io.*;
import java.util.*;
import java.util.stream.*;

class Combination<T> {
    private int n;
    private int r;
    private int[] now; // 현재 조합
    private List<List<T>> result; // 모든 조합

    public List<List<T>> getResult() {
        return result;
    }

    public Combination(int n, int r) {
        this.n = n;
        this.r = r;
        this.now = new int[r];
        this.result = new ArrayList<>();
    }

    public void combination(List<T> list, int depth, int index, int target) {
        if (depth == r) {
            List<T> temp = new ArrayList<>();
            for (int i = 0; i < now.length; i++) {
                temp.add(list.get(now[i]));
            }
            result.add(temp);
            return;
        }
        if (target == n) return;
        now[index] = target;
        combination(list, depth + 1, index + 1, target + 1);
        combination(list, depth, index, target + 1);
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        while (true) {
            StringTokenizer st = new StringTokenizer(br.readLine());

            int k = Integer.parseInt(st.nextToken());

            if (k == 0) {
                bw.flush();
                bw.close();
                break;
            }

            List<String> lotto = new ArrayList<>();

            for (int i = 0; i < k; i++) {
                String  num = st.nextToken();
                lotto.add(num);
            }

            Combination<String> comb = new Combination<>(k, 6);
            comb.combination(lotto, 0, 0, 0);

            List<List<String>> result = comb.getResult();

            for (List<String> lottoCase : result) {
                String answer = lottoCase.stream().collect(Collectors.joining(" "));
                bw.write(answer + "\n");
            }
            bw.write("\n");
        }
    }
}

BOJ 카테고리 내 다른 글 보러가기

댓글 남기기