Reputation: 11
How do I solve the 2nd part of this problem if the input array may contain repeated numbers and the value of K = 2
Examples:
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
My approach:
First, I count the different numbers in the array, then calculate an answer using DP (please see editorial of this problem).
Using those numbers, I tried some permutations, but the answer is incorrect.
I have already solve it with Time Complexity O(n^4),, is there any more efficient solution for this problem
Upvotes: 0
Views: 1110
Reputation: 1
Please don't answer now, Its question of ongoing contest.
[contest link][1]
https://www.codechef.com/MARCH16/problems/SEATSTR2
Upvotes: 0
Reputation: 419
Note: Code will be in Python, because it's easy. The logic should work for any language (more or less).
To reiterate the question:
You are given an array A = [1, 2, 3, ..., n]:
How many sequences (S2) can you get after at most k swaps on A?An adjacent swap can be made between two elements of the Array A, A[i] and A[i+1] or A[i] and A[i-1]. A swap otherwise can be between any two elements of the array A[i] and A[j] ∀ 1 ≤ i, j ≤ N, i ≠ j.
Let's address what we need to do:
Now, I can address each "requirement", one at a time.
D = [1,2,3,4]
, for examplemaster_list = []
perm_count(orig_list, k)
and permuter(my_list)
Python code used in pythonfiddle.com
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)
Upvotes: 1