Gym - 102082G

Gym - 102082G
https://vjudge.net/problem/2198225/origin
对于数列中任意一个数,要么从最左边到它不递减,要么从最右边到到它不递减,为了满足这个条件,就要移动,而移动的最少步数就是逆序对数。所以这个数要么往左移动,要么往右移动,所以两个取最小就好了

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#define inf 2147483647
#define ls rt<<1
#define rs rt<<1|1
#define lson ls,nl,mid,l,r
#define rson rs,mid+1,nr,l,r
#define N 1000010
#define For(i,a,b) for(long long i=a;i<=b;i++)
#define p(a) putchar(a)
#define g() getchar()

using namespace std;
long long n,len,ans,k;
long long a[N],b[N],c[N],temp,d1[N],d2[N];
long long t[N];
void in(long long &x){
    long long y=1;
    char c=g();x=0;
    while(c<'0'||c>'9'){
        if(c=='-')y=-1;
        c=g();
    }
    while(c<='9'&&c>='0'){
        x=(x<<1)+(x<<3)+c-'0';c=g();
    }
    x*=y;
}
void o(long long x){
    if(x<0){
        p('-');
        x=-x;
    }
    if(x>9)o(x/10);
    p(x%10+'0');
}

void modify(long long k){
    for(;k<=n;k+=k&(-k))
        t[k]++;
}

long long getnum(long long k){
    long long cnt=0;
    for(;k>0;k-=k&(-k))
        cnt+=t[k];
    return cnt;
}

int main(){
    in(n);
    For(i,1,n){
        in(a[i]);
        b[i]=a[i];
        c[i]=a[i];
    }
    sort(b+1,b+n+1);
    sort(c+1,c+n+1);
    len=unique(b+1,b+n+1)-b-1;
    For(i,1,n)
        a[i]=lower_bound(b+1,b+n+1,a[i])-b;
    For(i,1,n){
        modify(a[i]);
        d1[i]=i-getnum(a[i]);
    }
    memset(t,0,sizeof(t));
    for(long long i=n;i;i--){
        modify(a[i]);
        d2[i]=n-i-getnum(a[i])+1;
    }
    For(i,1,n)
        ans+=min(d1[i],d2[i]);
    o(ans);
    return 0;
}

 

posted @ 2019-07-17 11:13  WeiAR  阅读(265)  评论(0编辑  收藏  举报