Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- using ll = long long;
- using ld = long double;
- using ull = unsigned long long;
- const bool typetest = 0;
- const ll Inf = 1e17;
- const int N = 1e5 + 5;
- int n, k;
- int a[N];
- int cnt[12][12];
- ll dp[1 << 12], sum[12];
- vector<int> adj[N];
- void Read()
- {
- cin >> n >> k;
- for (int i = 1; i <= n; ++i)
- {
- cin >> a[i];
- adj[a[i]].push_back(i);
- }
- }
- #define bit(i, x) (((x) >> (i)) & 1)
- #define cal(x, y) (((y) - (x) + 1) * ((x) + (y))) / 2
- void Solve()
- {
- for (int i = 1; i <= k; ++i)
- for (auto j : adj[i])
- {
- for (int t = 1; t <= k; ++t)
- if (t != i)
- cnt[i][t] += adj[t].end() - lower_bound(adj[t].begin(), adj[t].end(), j);
- sum[i] += j;
- }
- for (int i = 1; i < (1 << k); ++i)
- {
- dp[i] = Inf;
- for (int j = 0; j < k; ++j)
- if (bit(j, i))
- {
- ll cost(0), pos(0);
- for (int t = 0; t < k; ++t)
- if (bit(t, i) && t != j)
- {
- pos += adj[t + 1].size();
- cost += cnt[j + 1][t + 1];
- }
- cost += sum[j + 1] - cal(pos + 1, pos + adj[j + 1].size());
- dp[i] = min(dp[i], dp[i ^ (1 << j)] + cost);
- }
- }
- cout << dp[(1 << k) - 1];
- }
- int32_t main()
- {
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- int t(1);
- if (typetest)
- cin >> t;
- for (int _ = 1; _ <= t; ++_)
- {
- Read();
- Solve();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement