ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준]1759: 암호 만들기 - JAVA
    문제풀이/백준 2021. 2. 11. 20:55

    [백준]1759: 암호 만들기

    www.acmicpc.net/problem/1759

     

    1759번: 암호 만들기

    첫째 줄에 두 정수 L, C가 주어진다. (3 ≤ L ≤ C ≤ 15) 다음 줄에는 C개의 문자들이 공백으로 구분되어 주어진다. 주어지는 문자들은 알파벳 소문자이며, 중복되는 것은 없다.

    www.acmicpc.net

    풀이

    순열을 사용한 백트랙킹문제!

     

    결과가 사전 순서대로 저장되어야 하므로 sort를 해주었다. 그리고 값을 뽑을때 알파벳이 증가하는 순서대로만 뽑아야 하므로 compareTo 메소드를 사용하여 이전의 뽑은 값과 비교해 주었다. 또한 모음인지 체크하는 함수를 만들어 주었고 조건에 모든 문자를 다 뽑은 후에는 모음의 수, 자음의 수가 조건에 맞는지 확인한 후 맞다면 출력하도록 해주었다. 

     

    별로 어렵지 않은 전형적인 순열 문제였다-!

     

    코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    import java.util.*;
     
    public class Main {    
        
        static String[] text;
        static int l, c;
        static boolean[] visited;
        
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            
            l = scan.nextInt();
            c = scan.nextInt();
            scan.nextLine();
            
            String str = scan.nextLine();
            text = str.split(" ");
            Arrays.sort(text);
            
            String[] result = new String[l];
            visited = new boolean[c];
            permutation(result, 000);
        }    
        
        public static void permutation(String[] result, int idx, int vowel, int consonant) {
            if(idx == l) {
                if(vowel >= 1 && consonant >= 2) {
                    for(int i = 0; i < l; i++) {
                        System.out.print(result[i]);
                    }
                    System.out.println();
                }
                return;
            }
            
            for(int i = 0; i < c; i++) {
                if(visited[i] == false) {
                    //이전에 뽑았던 값보다 사전순으로 더 큰값을 뽑아야 하며 처음 뽑는 경우에는 상관없다.
                    if(idx == 0 || result[idx - 1].compareTo(text[i]) < 0) { 
                        visited[i] = true;
                        result[idx] = text[i];
                        if(isVowel(text[i])) permutation(result, idx + 1, vowel + 1, consonant);
                        else permutation(result, idx + 1, vowel, consonant + 1);
                        visited[i] = false;
                    }
                }
            }
        }
        
        //모음체크
        public static boolean isVowel(String s) {
            if(s.equals("a"|| s.equals("e"|| s.equals("i"|| s.equals("o"|| s.equals("u")) {
                return true;
            }
            return false;
        }
    }
    cs

    댓글

Designed by Tistory.