학습일지/삼성 SDS 알고리즘 특강
삼성 SDS 대학생 알고리즘 특강 5일차 - 조합론
이재빵
2022. 7. 22. 23:24
728x90
1256: 사전
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N, M, K;
static int[][] dp = new int[201][201];
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
if (K > combination(N + M, M)) {
System.out.println("-1");
} else {
}
}
public static void query(int n, int m, int k) {
// 단어 끝에 도달
if (n + m == 0) {
return;
}
// z만 남은경우
else if (n == 0) {
sb.append('z');
query(n, m - 1, k);
}
// a만 남은경우
else if (m == 0) {
sb.append('a');
query(n - 1, m, k);
}
// a, z 둘다 남은 경우 a를 고를 때 조합 수를 보고 판단
else {
int leftCount = combination(n + m - 1, m);
if (leftCount >= k) {
sb.append('a');
query(n - 1, m, k);
} else {
sb.append('z');
query(n, m - 1, k - leftCount);
}
}
}
public static int combination(int n, int r) {
if (n == r || r == 0) {
return 1;
} else if (dp[n][r] != 0) {
return dp[n][r];
} else {
return dp[n][r] = Math.min((int) 1e9, combination(n - 1, r - 1) + combination(n - 1, r));
}
}
}
1722: 순열의 순서
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N;
static int[] nums;
static long[] fact = new long[21];
static long[][] dp;
static boolean[] visited;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
fact[0] = 1;
for (int i = 1; i <= 20; ++i) {
fact[i] = fact[i - 1] * i;
}
N = Integer.parseInt(br.readLine());
visited = new boolean[N + 1];
StringTokenizer st = new StringTokenizer(br.readLine());
int command = Integer.parseInt(st.nextToken());
if (command == 1) {
long target = Long.parseLong(st.nextToken());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
for (int j = 1; j <= N; j++) {
if (visited[j] == true) {
continue;
}
if (target > fact[N - i - 1]) {
target -= fact[N - i - 1];
} else {
sb.append(j);
sb.append(" ");
visited[j] = true;
break;
}
}
}
System.out.println(sb.toString());
} else if (command == 2) {
nums = new int[N];
for (int i = 0; i < N; i++) {
nums[i] = Integer.parseInt(st.nextToken());
}
long result = 0;
for (int i = 0; i < N; i++) {
for (int j = 1; j < nums[i]; j++) {
if (visited[j] == false) {
result += fact[N - i - 1];
}
}
visited[nums[i]] = true;
}
System.out.println(result + 1);
}
}
}