티스토리 뷰
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
59
60
61
62
63
64
65
66
67
|
import java.io.*;
import java.util.*;
public class boj_10971 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int N;
static int[][] prices = new int[11][11];
static int[] orders = new int[11];
public static void main(String[] args) throws IOException {
N = Integer.parseInt(br.readLine());
for (int i = 1; i <= N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 1; j <= N; j++) {
prices[i][j] = Integer.parseInt(st.nextToken());
}
}
for (int i = 1; i <= N; i++) {
orders[i] = i;
}
int min = Integer.MAX_VALUE;
do {
if (orders[1] != 1) break;
min = Math.min(min, getMin(orders, prices));
} while (next_permutation(orders, N));
System.out.println(min);
}
static int getMin(int[] orders, int[][] prices) {
if (prices[orders[N]][orders[1]] == 0) return Integer.MAX_VALUE;
int sum = prices[orders[N]][orders[1]];
for (int i = 1; i < N; i++) {
if (prices[orders[i]][orders[i+1]] == 0) return Integer.MAX_VALUE;
sum += prices[orders[i]][orders[i+1]];
}
return sum;
}
static boolean next_permutation(int[] a, int n) {
int i = n;
while (i > 1 && a[i-1] >= a[i]) i-=1;
if (i <= 1) return false;
int j = n;
while (a[j] <= a[i-1]) j-=1;
int temp = a[i-1];
a[i-1] = a[j];
a[j] = temp;
j = n;
while (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i += 1; j -= 1;
}
return true;
}
}
|
cs |
- 순열, 백트래킹
- 마을을 도는 순서를 N! 가지로 구할 수 있는데 N의 조건이 10까지니깐 순열을 이용할 수 있다.
- 마을을 순회하는 순서를 orders에 저장
- 만약에 갈 수 없는 마을이 있는 경우 넘어가고 아니면 비용 계산
- O ( N * N! ) 을 O ( N * (N-1)! ) 로 줄일 수 있다.
- if (orders[1] != 1) break; :: 시작 마을이 1번이 아니면 검사하지 않는다는 것인데 이유는 N조건을 보면 1번 마을은 무조건 존재할 수 밖에 없고 나중에 끝까지 순회하더라도 결국 첫 마을로 돌아와야하니까 1번 마을의 시작에 대해서만 검사해도 충분하다.
'PS > boj' 카테고리의 다른 글
boj)1759 - 암호 만들기 (0) | 2020.12.01 |
---|---|
boj)6603 - 로또 (0) | 2020.12.01 |
boj)10819 - 차이를 최대로 (0) | 2020.11.30 |
boj)10974 - 모든 순열 (0) | 2020.11.30 |
boj)10973 - 이전 순열 (0) | 2020.11.30 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- ㅇㄷㅇㅈ
- js array
- 김영한 JPA
- 프로그래머스 SQL
- Spring Security
- 백준
- 이펙티브자바 아이템60
- 김영한 http
- dreamcoding
- 드림코딩
- js promise
- 이펙티브자바
- 이펙티브자바 아이템59
- js api
- 패스트캠퍼스 컴퓨터공학 완주반
- HTTP 완벽가이드
- java
- 모던자바스크립트
- REST API
- 킹수빈닷컴
- JPA 연관관계 매핑
- HTTP 완벽 가이드
- GCP
- JS 딥다이브
- http
- BOJ
- 프로그래머스
- 이펙티브자바 스터디
- 백기선 스터디
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함