Hackerrank-Interview Preparation Kit-Arrays-New Year Chaos-Python

Output Format

Print an integer denoting the minimum number of bribes needed to get the queue into its final state. Print Too chaotic if the state is invalid, i.e. it requires a person to have bribed more than  people.

Sample Input

2
5
2 1 5 3 4
5
2 5 1 3 4

Sample Output

3
Too chaotic
#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumBribes function below.

def minimumBribes(q):
    moves = 0
    for pos, val in enumerate(q): ###########
        if (val-1) - pos > 2:
            print("Too chaotic")
            return
        for j in range(max(0,val-2), pos):
        # 从val对应的原坐标(val-1)的前一个(val-2) 到val的当前坐标(pos)中判断有多少个数字比val大,注意,如果(val-2)<0,则范围为(0,pos)。
            if q[j] > val:
                moves+=1
    print(moves)
    return

if __name__ == '__main__':
    t = int(input())

    for t_itr in range(t):
        n = int(input())

        q = list(map(int, input().rstrip().split()))

        minimumBribes(q)

 

Published 128 original articles · won praise 90 · views 4857

Guess you like

Origin blog.csdn.net/weixin_45405128/article/details/103987920