Advertisement
Josif_tepe

Untitled

Nov 14th, 2023
494
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5. using namespace std;
  6. const int maxn = 2002;
  7. const int INF = 1e9;
  8. vector<pair<int, int> > graph[maxn];
  9. int n;
  10. int dp[maxn][4100];
  11. int rek(int at, int number) {
  12.     if(at >= n) {
  13.         return 0;
  14.     }
  15.     if(dp[at][number] != -1) {
  16.         return dp[at][number];
  17.     }
  18.     int res = INF;
  19.     for(int i = 0; i < (int) graph[at].size(); i++) {
  20.         int nxt_number = graph[at][i].first;
  21.         int swaps = graph[at][i].second;
  22.        
  23.         if(number <= nxt_number) {
  24.             res = min(res, rek(at + 1, nxt_number) + swaps);
  25.         }
  26.     }
  27.     return dp[at][number] = res;
  28. }
  29. int main()
  30. {
  31.  
  32.     cin >> n;
  33.     vector<int> v(n);
  34.    
  35.     for(int i = 0; i < n; i++) {
  36.         cin >> v[i];
  37.     }
  38.     for(int i = 0; i < n; i++) {
  39.         for(int j = 0; j <= 4095; j++) {
  40.             dp[i][j] = -1;
  41.             if(__builtin_popcount(j) == __builtin_popcount(v[i])) {
  42.                 int swaps = __builtin_popcount(v[i] ^ j) / 2;
  43.                 graph[i].push_back(make_pair(j, swaps));
  44.             }
  45.         }
  46.     }
  47.    
  48.     cout << rek(0, 0) << endl;
  49.     return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement