每个输入包含一个测试用例。每个测试用例的第一行包含两个整数 n 和 k(1 <= n <= 100, 0 <= k <= 1000000000),接下来的 1 行,包含 n 个数字表示排列 A,其中等于0的项表示看不清的位置(不超过 10 个)。
输出一行表示合法的排列数目。
5 5 4 0 0 2 0
2
def permutation(nums, p, q, candicates): if p == q: candicates.append(list(nums)) else: for i in range(p, q): nums[i], nums[p] = nums[p], nums[i] permutation(nums, p + 1, q, candicates) nums[i], nums[p] = nums[p], nums[i] def computePairs(nums): n, cnt = len(nums), 0 for i in range(n - 1): for j in range(i + 1, n): if nums[i] < nums[j]: cnt += 1 return cnt if __name__ == "__main__": n, k = map(int, input().split()) nums = list(map(int, input().split())) normal = [num for num in nums if num != 0] # 未缺失数字 missing = list(set(range(1, n + 1)) - set(normal)) # 缺失数字 missCnt = len(missing) candicates = [] permutation(missing, 0, missCnt, candicates) # 缺失数字的全排列 count = 0 for candicate in candicates: # 把缺失数字填入原数组 arr = list(nums) ptr = 0 for i in range(n): if nums[i] == 0: arr[i] = candicate[ptr] ptr += 1 else: arr[i] = nums[i] # 暴力计算顺序对 if computePairs(arr) == k: count += 1 print(count)