Блог пользователя FifthThread

Автор FifthThread, история, 5 лет назад, По-английски

You are given an array A of N non negative integers. There are K empty slots from 1 to K. You have to arrange these N numbers into K slots( 2*K> =N). Each slot can contain at most two numbers filled into it. After all the integers have been placed into these slots, find the sum of bitwise AND of all the numbers with their respective slot numbers

Task: Determine the maximum possible sum

Note: Some slots may remain empty

Example A = [1,3,10,20,7,1] N = 5 K = 10 answer = 25

I did brute force and some test case passed.

How to do this question?

  • Проголосовать: нравится
  • +12
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
← Rev. 4  
Проголосовать: нравится +4 Проголосовать: не нравится

Lets make bipartite graph where we have N nodes on one side and 2*K nodes on other side here , and make edges between all nodes from left to all right, now you can apply maximal bipartite matching with max total weight(Hungarian algorithm). Here edge weight denotes bitwise AND value of connected node.

You can also apply dp bitmask to not getting into complex implementation just that dp bitmasking will be exponential in complexity while above can be solved in polynomial time.

»
5 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +3 Проголосовать: не нравится

The constraint in the problem was 2*K >= N.

»
5 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится +3 Проголосовать: не нравится

Take an array avail and for i=1 to i=K avail[i]=2 Now start recursion, for index i=0 to i=N-1. Put A[i] to any index from j=1 to j=K if avail[j]>0 and similarly recurse for the next state by reducing avail by 1. So a state is given by a vector i.e., vector avail and push index to it. So you can store the maximum value of a state in a map<vector,int>m so as to prevent repeated calculation.

»
5 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится 0 Проголосовать: не нравится

We can use a simple bitmasking dp, where dp(start,mask) will give the maximum sum, when all elements before start are used and bits which are '0' in mask are currently available.

Time complexity: O(N*2K*2^(2K))

dp(0,0) will be answer
»
5 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

I hope my solution is correct . Can anyone verify ?

Thanks in advance

»
4 года назад, скрыть # |
 
Проголосовать: нравится +8 Проголосовать: не нравится

This problem came in my test too, I used normal dp bitmask, with a catch! I used $$$3$$$-base system to represent my mask (instead of usual $$$2$$$ base system). $$$dp[mask]$$$ denotes the max value, such that the $$$i^{th}$$$ bit in the mask denotes no. of integers filled in $$$i^{th}$$$ slot (It can be $$$0,1,2$$$). $$$dp[0]=0$$$.

Time complexity: $$$O(K*3^K)$$$