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;
typedef long long ll;
#define int ll
typedef pair<int, int> pi;
typedef vector <int> vi;
typedef vector <pi> vpi;
typedef pair <pi,pi> pipi;
typedef pair<pi, ll> pii;
typedef set <ll> si;
typedef long double ld;
#define f first
#define s second
#define mp make_pair
#define FOR(i,s,e) for(int i=s;i<=int(e);++i)
#define DEC(i,s,e) for(int i=s;i>=int(e);--i)
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define lbd(x, y) lower_bound(all(x), y)
#define ubd(x, y) upper_bound(all(x), y)
#define aFOR(i,x) for (auto i: x)
#define mem(x,i) memset(x,i,sizeof x)
#define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define maxn 1000010
#define INF (ll)1e18
#define MOD 1000000007
typedef pair <vi, int> pvi;
typedef pair <int,pi> ipi;
typedef vector <pii> vpii;
#define DEBUG 0
int N,M;
int A[maxn],B[maxn];
int dp[maxn],fw[maxn];
void upd(int p,int v){
for (int i=p;i<=N;i+=i&(-i)) fw[i] += v;
}
int qry(int p){
int ans = 0;
for (int i=p;i>0;i-=i&(-i)) ans += fw[i];
return ans;
}
int idx[maxn];
int32_t main(){
fast;
cin >> N;
FOR(i,1,N) cin >> A[i];
FOR(i,1,N) B[A[i]] = i;
FOR(x,2,N){
dp[x] = INF;
int sm = 0,inv=0;
FOR(i,1,N) fw[i] = 0;
int co = 1;
FOR(i,1,N) if (A[i] <= x) idx[A[i]] = co++;
DEC(k,x,1){
inv += (x-k)-qry(B[k]);
upd(B[k],1);
sm += idx[k];
//if (x == 3 && k == 1) cout << "AAA " << sm << ' ' << inv << '\n';
dp[x] = min(dp[x], dp[k-1] + inv + x*(x+1)/2 - (k-1)*k/2 - sm);
}
//cout << dp[x] << ' ';
}
//cout << '\n';
cout << dp[N];
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |