제출 #706151

#제출 시각아이디문제언어결과실행 시간메모리
706151becaidoGroup Photo (JOI21_ho_t3)C++17
100 / 100
1705 ms134648 KiB
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx,popcnt,sse4,abm")
#include <bits/stdc++.h>
using namespace std;

#ifdef WAIMAI
#define debug(HEHE...) cout << "[" << #HEHE << "] : ", dout(HEHE)
void dout() {cout << '\n';}
template<typename T, typename...U>
void dout(T t, U...u) {cout << t << (sizeof...(u) ? ", " : ""), dout(u...);}
#else
#define debug(...) 7122
#endif

#define ll long long
#define Waimai ios::sync_with_stdio(false), cin.tie(0)
#define FOR(x,a,b) for (int x = a, I = b; x <= I; x++)
#define pb emplace_back
#define F first
#define S second

const int SIZE = 5005;

int n;
int a[SIZE], p[SIZE], add[SIZE];
int dp[SIZE];
int cnt[SIZE][SIZE], sum[SIZE][SIZE];

struct BIT {
    BIT() {fill(bit, bit + n + 1, 0);}
    int bit[SIZE];
    void upd(int pos, int x) {
        for (; pos <= n; pos += pos & -pos) bit[pos] += x;
    }
    int que(int pos) {
        int re = 0;
        for (; pos; pos -= pos & -pos) re += bit[pos];
        return re;
    }
    int que(int l, int r) {
        return que(r) - que(l - 1);
    }
    pair<int, int> sch(int s) {
        int pos = 0, k = 0;
        for (int i = __lg(n); i >= 0; i--) if (pos + (1 << i) <= n) {
            int to = k + bit[pos + (1 << i)];
            if (pos + (1 << i) <= s + to - 1) {
                pos += 1 << i;
                k = to;
            }
        }
        return {pos, k};
    }
} bit, bit2;

int Sum(int l, int r) {
    return (l + r) * (r - l + 1) / 2;
}

void solve() {
    cin >> n;
    FOR (i, 1, n) cin >> a[i], p[a[i]] = i;
    FOR (i, 1, n) {
        bit = BIT();
        FOR (j, i, n) {
            cnt[i][j] = cnt[i][j - 1] + bit.que(p[j]);
            bit.upd(p[j], 1);
        }
    }

    FOR (i, 1, n) {
        bit = bit2 = BIT();
        FOR (j, i, n) {
            int pos = p[j] + add[p[j]], k;
            bit.upd(pos, 1);
            bit2.upd(pos, pos);

            tie(pos, k) = bit.sch(i - 1);
            sum[i][j] = Sum(i, i + k - 1) - bit2.que(1, pos) + bit2.que(pos + 1, n) - Sum(i + k, j);
        }
        FOR (j, 1, p[i]) add[j]++;
    }

    FOR (i, 1, n) {
        dp[i] = INT_MAX;
        FOR (j, 0, i - 1) dp[i] = min(dp[i], dp[j] + sum[j + 1][i] + cnt[j + 1][i]);
    }
    cout << dp[n] << '\n';
}

int main() {
    Waimai;
    solve();
}
#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...