제출 #371232

#제출 시각아이디문제언어결과실행 시간메모리
371232cheissmartGroup Photo (JOI21_ho_t3)C++14
100 / 100
1530 ms67748 KiB
#include <bits/stdc++.h>
#define IO_OP std::ios::sync_with_stdio(0); std::cin.tie(0);
#define F first
#define S second
#define V vector
#define PB push_back
#define MP make_pair
#define EB emplace_back
#define ALL(v) (v).begin(), (v).end()
#define debug(x) cerr << "Line(" << __LINE__ << ") -> " << #x << " is " << x << endl

using namespace std;

typedef long long ll;
typedef pair<int, int> pi;
typedef V<int> vi;

const int INF = 1e9 + 7, N = 5005;

int a[N], p[N], dp[N], cost[N][N];

struct BIT {
	int bit[N];
	BIT() {
		memset(bit, 0, sizeof bit);
	}
	void add(int pos, int val) {
		for(; pos < N; pos += pos & -pos)
			bit[pos] += val;
	}
	int qry(int pos) {
		int res = 0;
		for(; pos; pos -= pos & -pos)
			res += bit[pos];
		return res;
	}
} b1, b2;

signed main()
{
	IO_OP;

	int n;
	cin >> n;
	for(int i = 1; i <= n; i++) {
		cin >> a[i];
		p[a[i]] = i;
	}

	for(int r = 1; r <= n; r++) {
		for(int i = 1; i <= r; i++) b1.add(p[i], 1);
		int ans = 0;
		for(int l = r; l >= 1; l--) {
			ans += b1.qry(n) - b1.qry(p[l]);
			ans -= b2.qry(p[l]);
			cost[l][r] = ans;
			b2.add(p[l], 1);
		}
		for(int l = r; l >= 1; l--) b2.add(p[l], -1);
		for(int i = 1; i <= r; i++) b1.add(p[i], -1);
	}

	dp[0] = 0;
	for(int i = 1; i <= n; i++) {
		dp[i] = INF;
		for(int j = 1; j <= i; j++) {
			dp[i] = min(dp[i], dp[j - 1] + cost[j][i]);
		}
	}
	cout << dp[n] << endl;

}

#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...