Submission #485363

#TimeUsernameProblemLanguageResultExecution timeMemory
485363PoPularPlusPlusGroup Photo (JOI21_ho_t3)C++17
100 / 100
468 ms452 KiB
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long 
#define pb(e) push_back(e)
#define sv(a) sort(a.begin(),a.end())
#define sa(a,n) sort(a,a+n)
#define mp(a,b) make_pair(a,b)
#define vf first
#define vs second
#define ar array
#define all(x) x.begin(),x.end()
const int inf = 0x3f3f3f3f;
const int mod = 1000000007; 
const double PI=3.14159265358979323846264338327950288419716939937510582097494459230;
bool remender(ll a , ll b){return a%b;}

struct Fen {
	
	vector<ll> tree;
	
	void init(int n){
		tree.assign(n + 1 , 0LL);
	}
	
	void set(int i , ll val , int n){
		i++;
		while(i <= n){
			tree[i] += val;
			i += (i & (-i));
		}
	}
	
	ll sum(int i){
		i++;
		ll ans = 0;
		while(i > 0){
			ans += tree[i];
			i -= (i & (-i));
		}
		return ans;
	}
	
	void build(vector<int>& a){
		int n = a.size();
		for(int i = 0; i < n; i++){
			set(i , a[i] , n);
		}
	}
	
};


void solve(){
	int n;
	cin >> n;
	int arr[n + 1];
	for (int i = 1; i <= n; i++) {
		cin >> arr[i];
	}
	int dp[n + 1];
	dp[0] = 0;
	int pos[n + 1];
	for (int i = 1; i <= n; i++) {
		for (int j = 1, cur = 1; j <= n; j++) {
			if (arr[j] <= i)
				pos[arr[j]] = cur++;
		}
		Fen ft;
		ft.init(n + 5);
		int cost = 0;
		dp[i] = 1e9;
		for (int j = i; j >= 1; j--) {
			int loc = pos[j] - ft.sum(pos[j]);
			cost += i - loc - 2 * ft.sum(pos[j] - 1);
			ft.set(pos[j], 1 , n + 2);
			dp[i] = min(dp[i], dp[j - 1] + cost);
		}
	}
	cout << dp[n];
}

int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
	//int t;cin >> t;while(t--)
	solve();
	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...