[BOJ] 1517 버블 소트

Time Lapse :NONE

1517.cpp

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <math.h>
#include <string>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cstdio>

using namespace std;

#define MAXSIZE 500001

int n;
int arr[MAXSIZE];
int temp[MAXSIZE];
long long ans = 0;

void merge_sort(int from, int mid, int to)
{
int i = from;
int j = mid+1;
int index = from;

while (i <= mid && j <= to)
{
if (arr[i] <= arr[j])
temp[index++] = arr[i++];
else
{
temp[index++] = arr[j++];
ans = ans + j-index;
}
}

if (i > mid)
{
for (int l = j; l <= to; l++)
temp[index++] = arr[l];
}
else
{
for (int l = i; l <= mid; l++)
{
temp[index++] = arr[l];
}
}

for (int l = from; l <= to; l++)
{
arr[l] = temp[l];
}
}

void merge(int from, int to)
{
int mid;

if (from < to)
{
mid = (from + to) / 2;
merge(from, mid);
merge(mid + 1, to);
merge_sort(from, mid, to);
}
}

int main(void)
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}

merge(0,n-1);
cout << ans<< endl;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/1517/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.