# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
961412 | noobcodur | Group Photo (JOI21_ho_t3) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
using ld = long double;
#define int long long
#define pii pair<int,int>
#define forn(i,j) for(int i = 0; i < j; ++i)
#define forrange(i,j,k) for(int i = j; i < k; ++i)
#define vi vector<int>
#define vpii vector<pii>
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
const int MOD = 1e9+7; const int INF = 1e17+1; const int maxN = 5e3+1;
void setIO(string name){
ios_base::sync_with_stdio(0);
cin.tie(0);
if(!name.empty()){
freopen((name + ".in").c_str(),"r",stdin);
freopen((name + ".out").c_str(),"w",stdout);
}
}
int dp[maxN],a[maxN],pos[maxN],small[maxN];
int bit1[maxN],bit2[maxN];
void update1(int idx){
while(idx < maxN){
bit1[idx]++; idx += idx&-idx;
}
}
int query1(int idx){
int res = 0;
while(idx){
res += bit1[idx]; idx -= idx&-idx;
}
return res;
}
void update2(int idx){
while(idx < maxN){
bit2[idx]++; idx += idx&-idx;
}
}
int query2(int idx){
int res = 0;
while(idx){
res += bit2[idx]; idx -= idx&-idx;
}
return res;
}
void init(int n){
forrange(i,1,n+1){
bit2[i] = 0;
}
}
signed main(){
setIO("");
int n; cin >> n;
forrange(i,1,n+1){
cin >> a[i]; pos[a[i]] = i;
}
dp[0] = 0;
forrange(i,1,n+1){
dp[i] = INF;
update1(pos[i]);
small[i] = query1(n)-query1(pos[i]);
int cost = 0;
for(int j = i; j; --j){
cost += small[j]; //number of elements k < j having pos[k] > pos[j]
cost += query2(n)-query2(pos[j]); //number of elements k > j, having pos[k] > pos[j]
cost -= query(pos[j]-1); //number of elements k > j, having pos[k] < pos[j]
dp[i] = min(dp[i],dp[j-1]+cost);
update2(pos[j]);
}
init(n);
}
cout << dp[n] << endl;
}