제출 #879014

#제출 시각아이디문제언어결과실행 시간메모리
879014frostray8653Group Photo (JOI21_ho_t3)C++17
100 / 100
525 ms392576 KiB
#include <bits/stdc++.h>
#define int long long
#define IO ios::sync_with_stdio(0), cin.tie(0);
#define FOR(i, a, b) for (int i = a; i <= b; i++)
using namespace std;
using pii = pair<int, int>;
void dbg() {;}
template<class T, class ...U>
void dbg(T a, U ...b) { cout << a << " "; dbg(b...); }
void ent() { cout << "\n"; }
const int INF = 1e16;
const int N = 5005;

int a[N], pos[N];
int cnt[2][N][N];
int dp[N];

signed main() {
    IO;

    int n;
    cin >> n;
    FOR(i, 1, n) {
        cin >> a[i];
        pos[a[i]] = i;
    }
    FOR(i, 1, n) {
        int x = pos[i];
        for (int j = 1; j <= n; j++) {
            cnt[0][i][j] = cnt[0][i - 1][j] + cnt[0][i][j - 1] - cnt[0][i - 1][j - 1];
            cnt[0][i][j] += (j == x);
        }
        for (int j = n; j >= 1; j--) {
            cnt[1][i][j] = cnt[1][i - 1][j] + cnt[1][i][j + 1] - cnt[1][i - 1][j + 1];
            cnt[1][i][j] += (j == x);
        }
    }
    // FOR(i, 1, n) {
    //     FOR(j, 1, n) dbg(cnt[1][i][j]);
    //     ent();
    // }

    fill(dp, dp + N, INF);
    dp[0] = 0;
    FOR(l, 1, n) {
        int cst = 0;
        FOR(r, l, n) {
            cst += cnt[1][l - 1][pos[r]] + (cnt[0][r - 1][pos[r]] - cnt[0][l - 1][pos[r]]);
            dp[r] = min(dp[r], dp[l - 1] + cst);
        }
        cst = 0;
        FOR(r, l, n) {
            cst += cnt[1][r - 1][pos[r]];
            dp[r] = min(dp[r], dp[l - 1] + cst);
        }
    }
    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...