[LuoguP2995] [USACO10NOV] cow pictures Cow Photographs

Topic Link

First, determine the number of reverse prosequence,

Then consider each of the front on the final number of the target sequence, that is, the smallest number becomes maximum

Set the minimum number of position \ (P \) , then the number of pairs increases the reverse \ (NP \) , reducing the \ (p-1 \)

#include<iostream>
#include<cstring>
#include<cstdio>
#define int long long
using namespace std;

const int MAXN=100010;

int n,a[MAXN],pos[MAXN],cnt,ans;

int tree[MAXN<<1];

inline int lowbit(int x){
    return x&(-x);
}

int query(int x){
    int ans=0;
    for(;x;x-=lowbit(x))
        ans+=tree[x];
    return ans;
}

inline void update(int x,int d){
    for(;x<=n;x+=lowbit(x))
        tree[x]+=d;
}

signed main()
{
    scanf("%lld",&n);
    for(int i=1;i<=n;++i){
        scanf("%lld",&a[i]);
        pos[a[i]]=i;
    }
    for(int i=1;i<=n;++i){
        cnt+=i-1-query(a[i]);
        update(a[i],1);
    }
    ans=cnt;
    for(int i=1;i<=n;++i){
        cnt+=n-pos[i]-pos[i]+1;
        ans=min(ans,cnt);
    }
    printf("%lld\n",ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/yjkhhh/p/11712600.html