HackerRank "New Year Chaos"

Two tricks here:

1. Counting no. of inversed pairs - using Merge Sort, nothing special

2. How to check 'chaotic'? We simply check if any number is over 2 slots away from its own slot : )

#!/bin/python3

import sys

ret = 0
def merge(arr1, arr2):
global ret
if not arr1: return arr2
if not arr2: return arr1
for v2 in arr2:
arr1.append(v2)
i = len(arr1) - 1
while(i > 0):
if arr1[i] < arr1[i - 1]:
arr1[i - 1],arr1[i] = arr1[i], arr1[i - 1]
i -= 1
ret += 1
else:
break
return arr1 def mergeSort(arr):
n = len(arr)
if (n < 2): return arr
return merge(mergeSort(arr[:n//2]), mergeSort(arr[n//2:])) T = int(input().strip())
for _ in range(T):
ret = 0
n = int(input().strip())
q = [int(q_temp) for q_temp in input().strip().split(' ')]
# your code goes here
bTooCh = False
for i in range(n):
if q[i] - i > 3:
bTooCh = True
break
if bTooCh:
print ("Too chaotic")
continue mergeSort(q)
print (ret)
上一篇:OpenCV计算点到直线的距离 数学法


下一篇:Ajax和JSON基础