티스토리 뷰

문제

https://www.acmicpc.net/problem/10819

풀이과정

완전탐색을 순열로 구현해서 푼 문제다. N의 범위가 작기 때문에 순열로 완전탐색을 해도 시간초과가 나지 않을 수 있다.
보통 N이 10이하면 순열로 문제를 풀어도 된다고 한다.

먼저 입력받은 배열을 sort()를 통해 정렬을 해준 후 next_permutation을 통해서 모든 순열을 돌면서 가장 차이가 큰 값을 찾는다.

소스코드

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int calculate(vector<int> &a)
{
    int result = 0;

    for (int i = 1; i < a.size(); i++)
    {
        result += abs(a[i - 1] - a[i]);
    }

    return result;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;

    cin >> n;

    vector<int> a(n);

    for (int i = 0; i < n; i++) cin >> a[i];

    sort(a.begin(), a.end());

    int ans = 0;

    do
    {
        int tmp = calculate(a);
        ans = max(ans, tmp);
    } while (next_permutation(a.begin(), a.end()));

    cout << ans << "\n";

    return 0;
}

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 1963번 소수 경로  (0) 2018.03.24
[백준] 1697번 숨바꼭질  (0) 2018.03.06
[백준] 1107번 리모컨  (1) 2018.03.05
[백준] 1476번 날짜 계산  (0) 2018.03.05
[백준] 1722번 순열의 순서  (0) 2018.03.05
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함