Advertisement
Dang_Quan_10_Tin

QBSORT

Mar 9th, 2021
708
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4. using ld = long double;
  5. using ull = unsigned long long;
  6.  
  7. const bool typetest = 0;
  8. const ll Inf = 1e17;
  9. const int N = 1e5 + 5;
  10. int n, k;
  11. int a[N];
  12. int cnt[12][12];
  13. ll dp[1 << 12], sum[12];
  14. vector<int> adj[N];
  15.  
  16. void Read()
  17. {
  18.     cin >> n >> k;
  19.     for (int i = 1; i <= n; ++i)
  20.     {
  21.         cin >> a[i];
  22.         adj[a[i]].push_back(i);
  23.     }
  24. }
  25.  
  26. #define bit(i, x) (((x) >> (i)) & 1)
  27. #define cal(x, y) (((y) - (x) + 1) * ((x) + (y))) / 2
  28.  
  29. void Solve()
  30. {
  31.     for (int i = 1; i <= k; ++i)
  32.         for (auto j : adj[i])
  33.         {
  34.             for (int t = 1; t <= k; ++t)
  35.                 if (t != i)
  36.                     cnt[i][t] += adj[t].end() - lower_bound(adj[t].begin(), adj[t].end(), j);
  37.             sum[i] += j;
  38.         }
  39.     for (int i = 1; i < (1 << k); ++i)
  40.     {
  41.         dp[i] = Inf;
  42.         for (int j = 0; j < k; ++j)
  43.             if (bit(j, i))
  44.             {
  45.                 ll cost(0), pos(0);
  46.                 for (int t = 0; t < k; ++t)
  47.                     if (bit(t, i) && t != j)
  48.                     {
  49.                         pos += adj[t + 1].size();
  50.                         cost += cnt[j + 1][t + 1];
  51.                     }
  52.                 cost += sum[j + 1] - cal(pos + 1, pos + adj[j + 1].size());
  53.                 dp[i] = min(dp[i], dp[i ^ (1 << j)] + cost);
  54.             }
  55.     }
  56.     cout << dp[(1 << k) - 1];
  57. }
  58.  
  59. int32_t main()
  60. {
  61.     ios::sync_with_stdio(0);
  62.     cin.tie(0);
  63.     cout.tie(0);
  64.     int t(1);
  65.     if (typetest)
  66.         cin >> t;
  67.     for (int _ = 1; _ <= t; ++_)
  68.     {
  69.         Read();
  70.         Solve();
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement