https://www.acmicpc.net/problem/1759
1759번: 암호 만들기
첫째 줄에 두 정수 L, C가 주어진다. (3 ≤ L ≤ C ≤ 15) 다음 줄에는 C개의 문자들이 공백으로 구분되어 주어진다. 주어지는 문자들은 알파벳 소문자이며, 중복되는 것은 없다.
www.acmicpc.net
백트래킹 문제이고 그렇게 어려운 문제는 아니엇습니다.
이번엔 자바로 풀엇습니다.
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static char lists[];
public static boolean bCheck[];
public static ArrayList<Character>save=new ArrayList<>();
public static ArrayList<String>anw=new ArrayList<>();
public static int l;
public static int C;
public static void backtracking(int k,int cnt){
if(cnt>=l){
String str="";
boolean balpa=false;
int bcnt=0;
for(int i=0;i<save.size();i++){
if(save.get(i)=='a'||save.get(i)=='e'||save.get(i)=='i'||save.get(i)=='o'||save.get(i)=='u'){
balpa=true;
}else{
bcnt++;
}
str+=save.get(i).toString();
}
if(balpa==true){
if(bcnt>=2){
anw.add(str);
}
}
return ;
}
for(int i=k;i<C;i++){
if(save.size()>0){
if(bCheck[i]==false&& save.get(save.size()-1)<lists[i] ){
save.add(lists[i]);
bCheck[i]=true;
backtracking(k,cnt+1);
bCheck[i]=false;
save.remove(save.size()-1);
}
}else{
if(bCheck[i]==false){
save.add(lists[i]);
bCheck[i]=true;
backtracking(k,cnt+1);
bCheck[i]=false;
save.remove(save.size()-1);
}
}
}
}
public static void main(String[] args) throws Exception {
Scanner scan=new Scanner(System.in);
l=scan.nextInt();
C=scan.nextInt();
char tmplists[]=new char[C];
scan.nextLine();
boolean tmpCheck[]=new boolean[C];
String tmp=scan.nextLine();
tmp=tmp.replaceAll(" ","");
for(int i=0;i<tmp.length();i++){
tmplists[i]=tmp.charAt(i);
tmpCheck[i]=false;
}
lists=tmplists;
bCheck=tmpCheck;
Arrays.sort( lists );
backtracking(0,0);
for(int i=0;i<anw.size();i++){
System.out.println(anw.get(i));
}
}
}
'알고리즘 공부' 카테고리의 다른 글
백준 배 (복습) (0) | 2023.11.20 |
---|---|
백준 트리(복습) (1) | 2023.11.20 |
백준 동전2(복습) (1) | 2023.11.15 |
백준 동전1(복습) (0) | 2023.11.13 |
백준 LCS 3 (0) | 2023.11.09 |