Advertisement
Josif_tepe

Untitled

Nov 14th, 2023
535
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 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.     int idx = (int) (lower_bound(graph[at].begin(), graph[at].end(), make_pair(number, 0)) - graph[at].begin());
  20.    
  21.     if(idx >= 0 and idx < graph[at].size()) {
  22.         for(int i = idx; i < (int) graph[at].size(); i++) {
  23.             int nxt_number = graph[at][i].first;
  24.             int swaps = graph[at][i].second;
  25.             res = min(res, rek(at + 1, nxt_number) + swaps);
  26.         }
  27.     }
  28.     return dp[at][number] = res;
  29. }
  30. int main()
  31. {
  32.  
  33.     cin >> n;
  34.     vector<int> v(n);
  35.    
  36.     for(int i = 0; i < n; i++) {
  37.         cin >> v[i];
  38.     }
  39.     for(int i = 0; i < n; i++) {
  40.         for(int j = 0; j <= 4095; j++) {
  41.             dp[i][j] = -1;
  42.             if(__builtin_popcount(j) == __builtin_popcount(v[i])) {
  43.                 int swaps = __builtin_popcount(v[i] ^ j) / 2;
  44.                 graph[i].push_back(make_pair(j, swaps));
  45.             }
  46.         }
  47.     }
  48.    
  49.     cout << rek(0, 0) << endl;
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement