[BOJ]5568カードを置く
🔗 Problem
https://www.acmicpc.net/problem/5568
👩💻 Code package baekjoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.io.IOException;
// 카드 놓기
public class BJ5568 {
static int n;
static int k;
static String[] arr;
static boolean[] visited;
static HashSet<String> set = new HashSet<>();
static StringBuilder sb;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
k = Integer.parseInt(br.readLine());
arr = new String[n];
visited = new boolean[n];
for(int i = 0; i < n; i++) {
arr[i] = br.readLine();
}
dfs(0, 0);
System.out.println(set.size());
}
private static void dfs(int level, int idx) {
if(level == k) {
String number = sb.toString();
if(!set.contains(number)) set.add(number);
return;
}
if(level == 0) sb = new StringBuilder();
for(int i = 0; i < n; i++) {
if(level != 0 && i == idx) continue;
if(!visited[i]) {
visited[i] = true;
sb.append(arr[i]);
dfs(level + 1, i);
visited[i] = false;
int start = sb.length() - arr[i].length();
sb.delete(start, sb.length());
}
}
}
}
💡 Learned 아이디어
package baekjoon;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.io.IOException;
// 카드 놓기
public class BJ5568 {
static int n;
static int k;
static String[] arr;
static boolean[] visited;
static HashSet<String> set = new HashSet<>();
static StringBuilder sb;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
k = Integer.parseInt(br.readLine());
arr = new String[n];
visited = new boolean[n];
for(int i = 0; i < n; i++) {
arr[i] = br.readLine();
}
dfs(0, 0);
System.out.println(set.size());
}
private static void dfs(int level, int idx) {
if(level == k) {
String number = sb.toString();
if(!set.contains(number)) set.add(number);
return;
}
if(level == 0) sb = new StringBuilder();
for(int i = 0; i < n; i++) {
if(level != 0 && i == idx) continue;
if(!visited[i]) {
visited[i] = true;
sb.append(arr[i]);
dfs(level + 1, i);
visited[i] = false;
int start = sb.length() - arr[i].length();
sb.delete(start, sb.length());
}
}
}
}
💡 Learned 아이디어
誰かに選んだカードを入れさせます.
Reference
この問題について([BOJ]5568カードを置く), 我々は、より多くの情報をここで見つけました https://velog.io/@ssoyeong/BOJ-5568-카드-놓기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol