Advertisement
i_am_wiz

sol1

Nov 24th, 2022 (edited)
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n;
  6. int a[20];
  7. int dp[10][1 << 20];
  8.  
  9. int bestPairing(int board, int mask) {
  10.     if(board == n + 1) return 0; // base case
  11.     if(dp[board][mask] != -1) {
  12.         return dp[board][mask]; // if ans already found in dp arr the return
  13.     }
  14.    
  15.     // if ans not already computed, then compute
  16.     int ans = 0;
  17.     for (int i = 0; i < 2 * n; ++i) {
  18.         for (int j = 0; j < 2 * n; ++j) {
  19.             if( (mask & ((1 << i) | (1 << j))) == 0 )
  20.                 ans = max(ans, board * abs(a[i] - a[j]) * gcd(a[i], a[j]) + bestPairing(board + 1, mask | (1 << i) | (1 << j)));
  21.         }
  22.     }
  23.     dp[board][mask] = ans; // store ans and then return
  24.     return dp[board][mask];
  25. }
  26.  
  27. int main() {
  28.  
  29.     cin >> n;
  30.     for (int i = 0; i < 2 * n; ++i) {
  31.         cin >> a[i];
  32.     }
  33.     memset(dp, -1, sizeof dp);
  34.     cout << bestPairing(1, 0) << endl;
  35.  
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement