POJ2299 Ultra-QuickSort 树状数组(求逆序数)+离散化

POJ2299 Ultra-QuickSort

#include <stdio.h>
#include <string.h>
#include <algorithm>
#define lowbit(x) x&-x//位操作
using namespace std;
const int MAX=5*1e5+5;
int aa[MAX],c[MAX],n;
struct node
{
    int val;
    int id;
}a[MAX];
bool cmp(node a,node b)
{
    return a.val==b.val?a.id<b.id:a.val<b.val;
}
void update(int x)
{
    while(x<=n)
    {
        c[x]++;
        x+=lowbit(x);
    }
}
int getsum(int x)
{
    int sum=0;
    while(x)
    {
        sum+=c[x];
        x-=lowbit(x);
    }
    return sum;
}
int main()
{
    while (~scanf ("%d",&n)&&n)//n!=0
    {
        long long ans=0;
        memset(c,0,sizeof(c));
        for(int k=1;k<=n;k++)
        {
            scanf("%d",&a[k].val);
            a[k].id=k;
        }
        sort(a+1,a+n+1,cmp);
        for(int k=1;k<=n;k++)//离散化
            aa[a[k].id]=k;
        for(int k=1;k<=n;k++)
        {
            update(aa[k]);
            ans+=k-getsum(aa[k]);
        }
        printf("%I64d\n",ans);//long long
    }
    return 0;
}

离散化:

//方法一 数组(n常数小于1e6)
#include <stdio.h>
#include <algorithm>
using namespace std;
const int MAX=1e5+5;
int aa[MAX];
struct node
{
    int val;
    int id;
}a[MAX];
bool cmp(node a,node b)
{
    return a.val==b.val?a.id<b.id:a.val<b.val;
}
int main ()
{
    int n;
    scanf ("%d",&n);
    for (int k=1;k<=n;k++)
    {
        scanf("%d",&a[k].val);
        a[k].id=k;
    }
    sort(a+1,a+n+1,cmp);
    for (int k=1;k<=n;k++)
        aa[a[k].id]=k;
    for (int k=1;k<=n;k++)
        printf("%d  ",aa[k]);
    return 0;
}
//方法二 数组+STL(n常数大于1e6)
#include <stdio.h>
#include <algorithm>
using namespace std;
const int MAX=1e5+5;
int aa[MAX],a[MAX];
bool cmp(int a,int b)
{
    return a<b;
}
int main ()
{
    int n;
    scanf ("%d",&n);
    for (int k=1;k<=n;k++)
    {
        scanf("%d",&a[k]);
        aa[k]=a[k];
    }
    sort(a+1,a+n+1,cmp);
    //去重返回重复元素的首地址
    int L=unique(a+1,a+n+1)-a-1;
    //二分查找a+1~a+L+1内与第一个大于b[k]的位置
    for (int k=1;k<=n;k++)
        aa[k]=lower_bound(a+1,a+L+1,aa[k])-a;
    for (int k=1;k<=n;k++)
        printf("%d ",aa[k]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nrtostp/article/details/80150542