# 백준 : 차이를 최대로(10819)
문제
https://www.acmicpc.net/problem/10819소스
(Github: https://github.com/wonjnlee/wallydev/blob/master/bj_10819_maximumdifference)#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <list>
#include <cmath>
using namespace std;
int numbers[9];
int main(void)
{
int count, temp;
int result = 0;
int maximum = 0;
int total = 1;
scanf("%d", &count);
for(int i=0; i<count; i++) scanf("%d", &numbers[i]);
temp = count;
while(temp != 0) {
total *= temp;
temp--;
}
sort(numbers, numbers + count);
for(int i=0; i<total; i++) {
result = 0;
for(int j=0; j<count-1; j++) {
result += abs(numbers[j] - numbers[j+1]);
}
maximum = max(maximum, result);
if(next_permutation(numbers, numbers + count)) {}
}
printf("%d\n", maximum);
return 0;
}
풀이
사실 문제는 굉장히 쉬운데, 이 포스팅을 하는 이유는 두가지 함수를 소개하고 싶어서였다.1. abs(x)
: x의 절대값을 구할 수 있는 함수이다.
2. next_permutation(x, y)
: x에서부터 y까지의 범위를 갖는 행렬을 오름차순으로 정렬할 때, 주어진 행렬의 바로 다음 오름차순 행렬을 구해주는 함수이다. 실제로 이 기능을 구현하는 것도 할 수 있겠지만, 이미 구현된 함수를 잘 활용하는 것 또한 기술이라고 생각한다.. (귀찮다는 것은 쓰지 않겠다)
3. prev_permutation(x, y)
: 2번 함수의 역기능이라고 보면 된다. 오름차순으로 정렬할 때 바로 이전의 행렬을 구해준다.
댓글
댓글 쓰기