我正试图解决黑客银行的问题New Year Chaos:
进一步的解释可以在页面上找到。例如,将“交换”队列表示为q,如果q = [2, 1, 5, 3, 4],则所需的交换数量为3:
#!/bin/python
import sys
T = int(raw_input().strip())
for a0 in xrange(T):
n = int(raw_input().strip())
q = map(int,raw_input().strip().split(' '))
# your code goes here
diff = [x - y for x, y in zip(q, range(1,n+1))]
if any([abs(el) > 2 for el in diff]):
print "Too chaotic"
else:
all_pairs = [(q[i], q[j]) for i in range(n) for j in range(i+1, n)]
inversions = [pair[0] > pair[1] for pair in all_pairs]
print inversions.count(True)
这里也是本地运行的代码版本:
^{pr2}$
对于给定的测试用例,脚本正确地打印数字3。但是,对于所有其他“隐藏”测试用例,它给出了错误的答案:
我还尝试了一个实现气泡排序的提交:#!/bin/python
import sys
def swaps_bubble_sort(q):
q = list(q) # Make a shallow copy
swaps = 0
swapped = True
while swapped:
swapped = False
for i in range(n-1):
if q[i] > q[i+1]:
q[i], q[i+1] = q[i+1], q[i]
swaps += 1
swapped = True
return swaps
T = int(raw_input().strip())
for a0 in xrange(T):
n = int(raw_input().strip())
q = map(int,raw_input().strip().split(' '))
# your code goes here
diff = [x - y for x, y in zip(q, range(1,n+1))]
if any([abs(el) > 2 for el in diff]):
print "Too chaotic"
else:
print swaps_bubble_sort(q)
但是同样的(失败的)结果。掉期的最小数量不等于倒数的数量还是泡沫分类的数量?在