문제 : https://www.acmicpc.net/problem/5054
[알고리즘풀이]
가게 N개를 방문하는 모든 경우의 수를 생각해 봐야 될 것 같으나, 사실은 가게의 집들을 Sort 한 후, 맨 앞에서부터 차례대로 가게를 방문하고 돌아오면 된다. 거리를 최소화해야 되기 때문에, 가게를 뒤죽박죽 방문할 필요가 없다.
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int t, n, N[20];
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> t;
while (t--) {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> N[i];
}
sort(N, N + n);
int ans = 0, cur = N[0], s = N[0];
for (int i = 0; i < n; i++) {
ans += abs(N[i] - cur);
cur = N[i];
}
ans += abs(s - cur);
cout << ans << '\n';
}
}
'Problem Solving > BOJ' 카테고리의 다른 글
[BOJ] 9252 : LCS 2 - travelbeeee (0) | 2019.10.29 |
---|---|
[BOJ] 9251 : LCS - travelbeeee (0) | 2019.10.29 |
[BOJ] 1654 : 랜선 자르기 - travelbeeee (0) | 2019.10.28 |
[BOJ] 15686 : 치킨 배달 - travelbeeee (0) | 2019.10.28 |
[BOJ] 2583 : 영역구하기 - travelbeeee (0) | 2019.10.28 |