Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 80412 | Accepted: 30110 |
Description
Ultra-QuickSort produces the output
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
Output
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
warnings:
AC code:
#include
#include
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;
}