
풀이.
세그먼트 트리로는 아직 풀지 못해서 병합정렬로 풀었다.
우선 문제의 버블 정렬은
두 요소 간 순서가 맞으면 가만히 놔두고 순서가 틀렸다면 숫자를 교환해야한다. 그리고 swqp의 횟수를 구해야한다.
병합 정렬을 이용하여 swap의 횟수를 구하였다.
소스코드.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 병합 정렬 풀이 | |
import sys | |
def mergeSort(start, end): | |
global count | |
if start < end: | |
mid = (start + end) // 2 | |
mergeSort(start, mid) | |
mergeSort(mid+1, end) | |
left = start | |
right = mid + 1 | |
tmp = [] | |
while left <= mid and right <= end: | |
if arr[left] <= arr[right]: | |
tmp.append(arr[left]) | |
left += 1 | |
else: | |
tmp.append(arr[right]) | |
right += 1 | |
count += (mid - left + 1) | |
if left <= mid: | |
tmp += arr[left:mid+1] | |
if right <= end: | |
tmp += arr[right:end+1] | |
for i in range(len(tmp)): | |
arr[start + i] = tmp[i] | |
input = sys.stdin.readline | |
count = 0 | |
n = int(input()) | |
arr = list(map(int, input().split())) | |
mergeSort(0, n-1) | |
print(count) |
'프로그래밍 > 백준' 카테고리의 다른 글
[백준] 16975. 수열과 쿼리 21 - 파이썬 (0) | 2021.09.25 |
---|---|
[백준] 1238. 파티 - 파이썬 (0) | 2021.09.24 |
[백준] 1766 문제집 - 파이썬 (0) | 2021.09.20 |
[백준] 3665. 최종 순위 - 파이썬 (0) | 2021.09.15 |
[백준] 2357 최솟값과 최댓값 - 파이썬 (0) | 2021.09.14 |