PAT (Advanced Level) 1101. Quick Sort (25)

树状数组+离散化

#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<algorithm>
using namespace std;

const int maxn=100000+10;
int a[maxn],ans[maxn],c[maxn],b[maxn];
int n;
map<int,int>m;

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

void update(int a,int b)
{
    for(int i=a;i<=n;i=i+lowbit(i)) c[i]+=b;
}

int get(int a)
{
    int res=0;
    for(int i=a;i>0;i=i-lowbit(i)) res+=c[i];
    return res;
}

void lsh()
{
    sort(b+1,b+1+n);
    for(int i=1;i<=n;i++) m[b[i]]=i;
}

int main()
{
    scanf("%d",&n);
    int k=0;
    memset(c,0,sizeof c);
    m.clear();
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        b[i]=a[i];
    }
    lsh();
    for(int i=1;i<=n;i++)
    {
        if(m[a[i]]==i)
        {
            int num=get(m[a[i]]-1);
            if(num==m[a[i]]-1) ans[k++]=m[a[i]];
        }
        update(m[a[i]],1);
    }
    sort(ans,ans+k);
    printf("%d\n",k);
    for(int i=0;i<k;i++)
    {
        printf("%d",b[ans[i]]);
        if(i<k-1) printf(" ");
    }
    printf("\n");
    return 0;
}

 

posted @ 2016-07-05 08:41  Fighting_Heart  阅读(133)  评论(0编辑  收藏  举报