Submission #375753

#TimeUsernameProblemLanguageResultExecution timeMemory
375753rama_pangGroup Photo (JOI21_ho_t3)C++14
100 / 100
451 ms640 KiB
#include <bits/stdc++.h>
using namespace std;

template<typename T>
class Fenwick {
 public:
  int n;
  vector<T> tree;

  Fenwick(int n) : n(n), tree(n) {}

  void Modify(int p, T x) {
    for (int i = p; i < n; i |= i + 1) {
      tree[i] += x;
    }
  }

  T Query(int p) {
    T res = 0;
    for (int i = p; i > 0; i &= i - 1) {
      res += tree[i - 1];
    }
    return res;
  }
};

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);

  int N;
  cin >> N;

  vector<int> H(N);
  for (int i = 0; i < N; i++) {
    cin >> H[i];
    H[i]--;
  }

  // "sorted" = split H[0...N-1] into K segments,
  // such that in each segment:
  // H[i] == H[i + 1] + 1
  // is satisfied.

  vector<int> dp(N + 1, INT_MAX);
  dp[0] = 0;

  for (int i = 0; i < N; i++) {
    vector<int> A;
    vector<int> pos(N, -1);
    for (int j = 0; j < N; j++) {
      if (H[j] >= i) {
        pos[H[j]] = A.size();
        A.emplace_back(H[j]);
      }
    }
    int sum_pos = 0;
    int inversion = 0;
    Fenwick<int> F(A.size());
    for (int j = 1; i + j <= N; j++) { // segment = [i, i + j - 1]
      F.Modify(pos[i + j - 1], 1);
      sum_pos += pos[i + j - 1] - (j - 1); // place [i, i + j - 1] in front in any order
      inversion += F.Query(pos[i + j - 1]) ; // sort [i, i + j - 1] in descending order
      dp[i + j] = min(dp[i + j], dp[i] + sum_pos + inversion);
    }
  }

  cout << dp[N] << '\n';
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...