๋ฐ์ํ
https://www.acmicpc.net/problem/15650
์ฝ๋
import java.util.Scanner;
public class Main {
public static int arr[];
public static boolean visit[];
public static int N;
public static int M;
public static StringBuilder sb = new StringBuilder();
public static void dfs(int count) {
if(count == M) {
for(int i=0; i<M-1; i++) {
if(arr[i] > arr[i+1])
return;
}
for(int i : arr)
sb.append(i + " ");
sb.append("\n");
return;
}
for(int i=1; i<=N; i++) {
if(!visit[i]) {
visit[i] = true;
arr[count] = i;
dfs(count+1);
visit[i] = false;
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
N = scan.nextInt();
M = scan.nextInt();
arr = new int[M];
visit = new boolean[N+1];
dfs(0);
System.out.println(sb);
scan.close();
}
}
ํ์ด
N๊ณผ M (1)๋ฒ ๋ฌธ์ ์ ๋์ผํ์ง๋ง ์ฐจ์ด์ ์,
โ ๊ณ ๋ฅธ ์์ด์ด ์ค๋ฆ์ฐจ์์ด์ด์ผ ํ๋ค.
์ ํ๋๋ฐ์ ์๋ค.
๋ฐ๋ผ์ M๊ฐ๋งํผ ์์ด์ ๊ณจ๋์ ๋, ๊ณ ๋ฅธ ์์ด์ด ์ค๋ฆ์ฐจ์์ด ์๋๊ฒฝ์ฐ ์๋ฌด๋ฐ ์ํ ์์ด ์ข ๋ฃํด์ฃผ๊ณ ,
์ค๋ฆ์ฐจ์์ผ ๊ฒฝ์ฐ StringBuilder ์ ์ ์ฅํ๋ค.
if(count == M) {
for(int i=0; i<M-1; i++) {
if(arr[i] > arr[i+1])
return;
}
for(int i : arr)
sb.append(i + " ");
sb.append("\n");
return;
}
๋ฐ์ํ
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2217๋ฒ: ๋กํ(๊ทธ๋ฆฌ๋, ์ํ) (0) | 2020.02.19 |
---|---|
[Codeforces] 1154A - Restoring Three Numbers (0) | 2020.02.19 |
[๋ฐฑ์ค] 15649๋ฒ: N๊ณผ M (1) (dfs, ๋ฐฑํธ๋ํน) (0) | 2020.02.18 |
[๋ฐฑ์ค] 6986๋ฒ: ์ ์ฌํ๊ท (0) | 2020.02.14 |
[Codeforces] 791A: Bear and Big Brother (0) | 2020.02.13 |
๋๊ธ