Advertisement
S_Aditya

Untitled

Mar 24th, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4.  
  5. int main()                  
  6. {
  7.     int n; cin >> n;
  8.  
  9.     ll a[n], b[n];
  10.  
  11.     for(int i = 0; i < n; i++)
  12.     cin >> a[i];
  13.  
  14.     for(int i = 0; i < n; i++)
  15.     cin >> b[i];
  16.    
  17.     //initialise the dp array
  18.     ll dp[1 << n];
  19.  
  20.     for(int mask = 0; mask < (1 << n); mask++)
  21.     dp[mask] = INT_MIN;
  22.  
  23.     dp[0] = 0;
  24.  
  25.     for(int mask = 0; mask < (1 << n); mask++)
  26.     {
  27.         int len = __builtin_popcount(mask);
  28.  
  29.         //claiming that 'bit' will be the index at position len and use optimal
  30.         //answer for the previous part, as answer for previous part is independent
  31.         //of the value we are placing here. The only thing which changes is the indexes
  32.         //which are available with us, and to keep it's track we are using bitmasks.
  33.         for(int bit = 0; bit < n; bit++)
  34.         if(mask & (1 << bit))
  35.         {
  36.             //switch current bit off to get the previous mask
  37.             int nmask = mask ^ (1 << bit);
  38.  
  39.             dp[mask] = max(dp[mask], a[bit] * b[len - 1] + dp[nmask]);
  40.         }
  41.     }
  42.  
  43.     int full_mask = (1 << n) - 1;
  44.  
  45.     cout << dp[full_mask];
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement