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

Автор AjaySabarish, история, 3 года назад, По-английски

You are given an array of N integers (N is even), at each round you have to select 2 numbers $$$(A[i],A[j])$$$, and do $$$ Sum = Sum + GCD(A[i], A[j]) * round $$$, post calculating sum remove those 2 numbers from Array. What is the maximum possible sum you can obtain?

Round's value starts from 1.

Constraints

$$$ 2 \leq N \leq 20 $$$

$$$ 1 \leq A[i] \leq 1e9 $$$

I tried Bitmasking Dp ( $$$ O(2 ^N * N ^2) $$$ ) but got TLE.

Example :

2 3 5 9

1st Round — 2 5, Sum = GCD(2,5) * 1

2nd Round — 3 9, Sum = GCD(3,9) * 2

The maximum possible sum is 7

Any insights?

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

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I did the same and got AC, u did it in recursive or iterative approach?

  • »
    »
    3 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    recursion

  • »
    »
    3 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    can u explain the solution i was only getting 15/25 tc

    • »
      »
      »
      3 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      for mask : [1, 2^20]: for ith setbit in mask: for jth setbit in mask: dp[mask] = max(dp[mask], dp[mask ^ (1 << i) ^ (1 << j)] + (gcd(a[i],a[j]) * m))

      where 'm' refers to the round number that can be found for every mask in constant time.

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

same problem

but it is having constraints as N <= 14.

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Even I also did the same thing and got TLE.

»
3 года назад, # |
  Проголосовать: нравится +19 Проголосовать: не нравится

Precompute all GCDs

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

how does this state work, dp[mask] = max gcd pairwise sum you can achieve from bits present in mask

i wrote code with this as state and it passed all test cases except one due to recursion

I also wrote dp like this dp[mask][R] = max gcd pairwise sum you can achieve from bits present in mask and the current round is R,

I feel that the second dp notation has correctness in it, but for the first case since the round information is missing

my code: https://ideone.com/2Q4I3m , same code after removing the second state which stores the round number also passed.

my doubt is around the correctness of the first dp notation where we are only memoizing the mask

  • »
    »
    3 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Notice that popcount/2 + 1 is the round number for particular mask (ignoring odd bits masks), hence round is a redundant state and need not to be present