티스토리 뷰
방문해야할 곳은 회사 - N개의 고객 - 집 이렇게 12개다
그럼 회사와 집은 고정시켜두고 N개를 next_permutation을 통해 확인하면 된다
10!이기 때문에 시간은 충분하게 나온다!
소스코드 ( Java)
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
|
public class Solution {
public static int[] order = new int[10];
public static int[][] arr = new int[10][2];
public static int ox,oy,hx,hy,n,ans;
public static int dist(int x1,int y1,int x2,int y2) {
}
public static void swap(int x,int y) {
int temp = order[x];
order[x]=order[y];
order[y]=temp;
}
public static int number() {
int ret = dist(ox,oy,arr[order[0]][0],arr[order[0]][1]);
for (int i = 0; i < n-1; i++) ret += dist(arr[order[i]][0], arr[order[i]][1], arr[order[i + 1]][0], arr[order[i + 1]][1]);
ret += dist(arr[order[n - 1]][0], arr[order[n - 1]][1], hx, hy);
return ret;
}
public static void solve(int now) {
if(now==n-1) {
ans = Math.min(ans, number());
return;
}
for(int i=now;i<n;i++) {
swap(i,now);
solve(now+1);
swap(i,now);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t= sc.nextInt();
for(int tc=1;tc<=t;tc++) {
n = sc.nextInt();
for(int i=0;i<n;i++) order[i]=i;
ox=sc.nextInt(); oy=sc.nextInt();
hx=sc.nextInt(); hy=sc.nextInt();
for(int i=0;i<n;i++) {
arr[i][0]=sc.nextInt();
arr[i][1]=sc.nextInt();
}
ans = Integer.MAX_VALUE;
solve(0);
System.out.println("#"+tc+" "+ans);
}
}
}
|
소스코드(C++)
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
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int order[10];
int arr[10][2];
int officeX, officeY, houseX, houseY;
int dist(int x1, int y1, int x2, int y2) {
return(abs(x1 - x2) + abs(y1 - y2));
}
int main() {
int t; scanf(" %d", &t);
for (int tc = 1; tc <= t; tc++) {
int n; scanf(" %d", &n);
for (int i = 0; i < n; i++) order[i] = i;
scanf("%d %d %d %d", &officeX, &officeY, &houseX, &houseY);
for (int i = 0; i < n; i++) scanf(" %d %d", &arr[i][0], &arr[i][1]);
int ans = 1e9;
do {
int temp = dist(officeX, officeY, arr[order[0]][0], arr[order[0]][1]);
for (int i = 0; i < n-1; i++) temp += dist(arr[order[i]][0], arr[order[i]][1], arr[order[i + 1]][0], arr[order[i + 1]][1]);
temp += dist(arr[order[n - 1]][0], arr[order[n - 1]][1], houseX, houseY);
ans = min(ans, temp);
} while (next_permutation(order,order+n));
printf("#%d %d\n", tc, ans);
}
}
|
'알고리즘 > SW Expert Academy' 카테고리의 다른 글
[SWEA] 8382 방향전환 (0) | 2020.03.03 |
---|---|
[SWEA] 4534 트리 흑백 색칠 (0) | 2020.03.02 |
[SWEA] 4408 자기 방으로 돌아가기 (0) | 2020.02.11 |
[SWEA] 1225 암호생성기 (0) | 2020.02.03 |
[SWEA] 1855 영준이의 진짜 BFS (0) | 2020.01.15 |
댓글