Josif_tepe

Untitled

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