在最多2次掉期后计算不同的排列

时间:2016-03-07 13:20:49

标签: algorithm combinations dynamic-programming

如果输入数组可能包含重复数字且值 K = 2

,如何解决this problem的第二部分

示例:

1 2 3 4     ans-18
1 2 3 4 5   ans-46
1 1 2 2 3   ans-26
1 1 1 2 2   ans-10
1 1 2 2 3 4 ans-56 

我的方法:
首先,我计算数组中的不同数字,然后使用DP计算答案(请参阅此问题的编辑) 使用这些数字,我尝试了一些排列,但答案是错误的。

我已经用Time Complexity O(n ^ 4)解决了它,是否有更有效的解决方案来解决这个问题

2 个答案:

答案 0 :(得分:1)

注意:代码将在Python中,因为它很容易。逻辑应适用于任何语言(或多或少)。

重申这个问题:

  

给你一个数组A = [1,2,3,...,n]:
  在A上最多k个交换后,你能得到多少个序列(S2)?

     

可以在阵列A,A [i]和A [i + 1]或A [i]和A [i-1]的两个元素之间进行相邻交换。   否则交换可以在数组A [i]和A [j]∀1≤i之间的任何两个元素之间,j≤N,i≠j。

让我们来解决我们需要做的事情:

  • 制作一系列清单(我将使用清单列表)
  • 制作一些操纵列表的功能
  • 查找交换所有原始列表中任意两个元素的所有结果
    • 对原始列表的最新迭代重复N-1次

现在,我可以一次一个地解决每个“要求”。

  1. 列表清单
    • 我想设置我稍后会测试的列表变量:D = [1,2,3,4],例如
    • master_list = []
  2. 我的功能将是perm_count(orig_list, k)permuter(my_list)
    • perm_count将成为我们的“经理”,将元素添加到列表列表中
    • permuter会做我们的腿部工作,找到掉期并将它们归还给perm_count
  3. 我们将使用循环查看上一次迭代中的所有列表,并找到其中的所有交换。 (你会在代码中看到)
    • 需要注意的一点是,根据语言的不同,在开始每个“k”循环的情况下获取列表的“快照”非常重要,否则在您处理它时列表会增长。< / LI>
    • 把它全部放在另一个循环中然后我们走了!
  4. pythonfiddle.com

    中使用的Python代码
    A = [1,2,3,4,5]  
    B = [1,1,2,2,3]  
    C = [1,2,3]  
    D = [1,2,3,4]
    
    def perm_count(orig_list, k):
    
    master_list  = []
    master_list.append(list(orig_list))
    while k > 0:
        big_list = list(master_list) #"Snapshot" to ensure list-stability
        for each_list in big_list: #Looks at all the permutations from the previous "generations"
            for each_temp_list in permuter(each_list):
                if each_temp_list not in master_list:
                    master_list.append(each_temp_list)
                    #our masterlist now contains all the distinct lists from this run
                    #If we run it again (the "k"), we get 2-swap combinations
                    #and so on...
    
        k-=1
    
    total_count = len(master_list)
    print sorted(master_list) #If you need a sanity check, feel free to leave out
    return total_count
    #end perm_count
    
    def permuter(my_list):#returns a list of lists
        lists_list = []
        #The below loop block returns all possible 1-swap combinations.
        for i in range(len(my_list)):
            for j in range(len(my_list)):
                temp_list = my_list[:]
                if i != j:
                    temp_list[i],temp_list[j] = temp_list[j],temp_list[i]
                if temp_list not in lists_list:
                    lists_list.append(list(temp_list))
    
        return lists_list
    #end permuter
    
    print perm_count(B,2)
    

答案 1 :(得分:0)

现在请不要回答,这是正在进行的比赛的问题。

[contest link][1]

https://www.codechef.com/MARCH16/problems/SEATSTR2