Submission #670560

#TimeUsernameProblemLanguageResultExecution timeMemory
670560MilosMilutinovicGroup Photo (JOI21_ho_t3)C++14
100 / 100
543 ms196428 KiB
#include <bits/stdc++.h>

using namespace std;

template <typename T>
class fenwick {
  public:
  vector<T> fenw;
  int n;
  fenwick(int _n) : n(_n) {
    fenw.resize(n);
  }
  void modify(int x, T v) {
    while (x < n) {
      fenw[x] += v;
      x |= (x + 1);
    }
  }
  T get(int x) {
    T v{};
    while (x >= 0) {
      v += fenw[x];
      x = (x & (x + 1)) - 1;
    }
    return v;
  }
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> h(n);
  for (int i = 0; i < n; i++) {
    cin >> h[i];
  }
  vector<int> pos(n + 1);
  for (int i = 0; i < n; i++) {
    pos[h[i]] = i;
  }
  vector<vector<long long>> f(n + 1, vector<long long>(n + 1));
  fenwick<int> fenw(n);
  for (int i = 1; i <= n; i++) {
    fenwick<int> pref(n);
    for (int j = i; j <= n; j++) {
      f[i][j] = f[i][j - 1] + fenw.get(n - 1) - fenw.get(pos[j]) + pref.get(pos[j]);
      pref.modify(pos[j], +1);
    }
    fenw.modify(pos[i], +1);
  }
  const int inf = 1e9;
  vector<long long> dp(n + 1, inf);
  dp[0] = 0;
  for (int i = 0; i < n; i++) {
    for (int j = i + 1; j <= n; j++) {
      dp[j] = min(dp[j], dp[i] + f[i + 1][j]);
    }
  }
  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...