POJ-2299-Ultra-QuickSort- merge sort Numbers by reverse

Verbatim https://www.dazhuanlan.com/2019/08/26/5d62f77c1b321/


Description

Subject to the effect, give you a bunch of different elements of each sequence, we can only swap two adjacent elements, find the minimum number of times so that the exchange can become a rising sequence sequence.

Note: to understand a rule, a number x, it must be exchanged and it left and it's bigger than the number that find the number in reverse order.

struct node{
    int elem;
    int old;
};
node arr[500010];
int a[500010];
int c[500010];
int n;
int cmp(node a, node b)
{
    return a.elem <= b.elem;
}
int main()
{
    int i;
    while(scanf("%d", &n) && n)
    {
        memset(c, 0, sizeof(c));
        arr[0].elem = -1;
        arr[0].old = 0;
        for(i = 1; i <= n; i )
        {
            scanf("%d", &arr[i].elem);
            arr[i].old = i;
        }
        sort(arr, arr n 1, cmp);//排序
        for(i = 1; i <= n; i )//将新排好序的下标一一对应存下来;
        {
            a[arr[i].old] = i;
        }
        double sum_ = 0;
        for(i = 1; i <= n; i )
        {
            add(a[i], 1);//将这个数插入
            sum_ = i - sum(a[i]);//得到比当前这个数大,并且初始时在它的左边的数的个数;即得到它的最优移动次数。
        }
        printf("%.0lfn", sum_);
    }
    return 0;
}
int lowbit(int x)
{
    return x&(-x);
}
double sum(int end_)
{
    double sum = 0;
    while(end_ > 0)
    {
        sum = c[end_];
        end_ -= lowbit(end_);
    }
    return sum;
}
void add(int i, int elem)
{
    while(i <= n)
    {
        c[i] = elem;
        i = lowbit(i);
    }
    return ;
}

Guess you like

Origin www.cnblogs.com/petewell/p/11410425.html