BOJ : https://www.acmicpc.net/problem/10090

github : https://github.com/junho0956/Algorithm/blob/master/10090/10090/%EC%86%8C%EC%8A%A4.cpp

 

도치수는 merge_sort 를 이용한 분할정복으로 해결할 수 있습니다.

 

더보기
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
#include <iostream>
using namespace std;
 
#define MAX 1000000
 
int arr[MAX];
int dup[MAX];
 
long long partition(int s, int m, int e) {
    int left = s, right = m + 1;
    int index = 0;
    long long result = 0;
    while (left <= m && right <= e) {
        if (arr[right] >= arr[left]) {
            dup[index++= arr[left++];
        }
        else {
            result += m - left + 1;
            dup[index++= arr[right++];
        }
    }
 
    while (left <= m) dup[index++= arr[left++];
    while (right <= e) dup[index++= arr[right++];
 
    for (int i = 0; i <= e - s; i++) {
        arr[s + i] = dup[i];
    }
 
    return result;
}
 
long long merge_sort(int s, int e) {
    long long result = 0;
    if (s < e) {
        int pivot = (s + e) / 2;
        result += merge_sort(s, pivot);
        result += merge_sort(pivot + 1, e);
        result += partition(s, pivot, e);
    }
    return result;
}
 
 
int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    int N; cin >> N;
 
    for (int i = 0; i < N; i++cin >> arr[i];
 
    long long result = merge_sort(0, N - 1);
 
    cout << result;
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

'algorithm > BOJ' 카테고리의 다른 글

BOJ 2875번 대회or인턴  (0) 2020.01.17
BOJ 11047번 동전 0  (0) 2020.01.17
BOJ 1517번 버블 소트  (0) 2020.01.17
BOJ 1992번 쿼드트리  (0) 2020.01.17
BOJ 1780번 종이의 개수  (0) 2020.01.17

+ Recent posts