菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
133
0

poj-2299

原创
05/13 14:22
阅读数 12881
Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 80412   Accepted: 30110

Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,

Ultra-QuickSort produces the output
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

Source

OJ-ID: poj-2299
author:Caution_X
date of submission:20191121
tags:merge_sort
description modelling:
计算将一个数列变成正序数列至少需要几次操作。
操作:交换相邻两个数的位置
major steps to solve it:
(1)归排
(2)在归排的子过程中若出现i<j&&a[i]>a[j],ans+=(j-j即将变换到的位置)。
warnings:
AC code:
#include<cstdio>
#include<algorithm>
using namespace std;
int a[500005];
int tmp[500005];
long long int num = 0;
void merge(int left, int mid, int right)
{
    int i = left, j = mid + 1, n = left;
    while (i <= mid && j <= right)
    {
        if (a[i] > a[j])
        {
            tmp[n++] = a[j++];
            num += (j - n);
        }
        else
        {
            tmp[n++] = a[i++];
        }
    }
    if (i > mid)
    {
        while (j <= right)
            tmp[n++] = a[j++];
    }
    else
    {
        while (i <= mid)
            tmp[n++] = a[i++];
    }
    for (int k = left; k <= right; k++)
    {
        a[k] = tmp[k];
    }
}
void mergesort(int left, int right)
{
    if (left < right)
    {
        int mid = (left + right) / 2;
        mergesort(left, mid);
        mergesort(mid + 1, right);
        merge(left, mid, right);
    }
}
int main()
{
    int n;
    //freopen("input.txt", "r", stdin);
    while (~scanf("%d", &n) && n)
    {
        num = 0;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        mergesort(0, n - 1);
        printf("%lld\n", num);
    }
    return 0;
}

发表评论

0/200
133 点赞
0 评论
收藏
为你推荐 换一批