-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1013.cpp
More file actions
66 lines (66 loc) · 1.73 KB
/
Copy path1013.cpp
File metadata and controls
66 lines (66 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <cstdio>
using namespace std;
void mysort(int*, int*, int, int, int&);
int main()
{
int m;
scanf("%d", &m);
int buf[50000];
for (int i = 0;i < m;i++)
{
int n;
scanf("%d", &n);
int temp[50000] = {};
for (int j = 0;j < n;j++)
{
scanf("%d", &temp[j]);
}
int result = 0;
mysort(temp, buf, 0, n - 1, result);
printf("%d", result);
}
}
// 用暴力方法做会超时,需要使用归并排序,在排序的过程中求出逆序数
// 有两个考虑角度,以下面的归并过程为例,假设有两个已经排序的序列等待
// 合并,分别是L={8, 12, 16, 22, 100}和R={9, 26, 55, 64, 91},在
// 归并的过程中如果碰到左指针的数比右指针的数大,假设现在左指针指向12,
// 右指针指向9,我们既可以认为是12排在9后面贡献了一个逆序,也可以认为是
// 9排在12, 16, 22, 100后面贡献了4个逆序,不难验证这两种思路最后得到的
// 结果是一样的。
void mysort(int* data, int* temp, int head, int tail, int& count)
{
if (head >= tail)
return;
int middle = (head + tail) >> 1;
mysort(data, temp, head, middle, count);
mysort(data, temp, middle + 1, tail, count);
int leftptr = head;
int rightptr = middle + 1;
int tempptr = head;
while (leftptr <= middle && rightptr <= tail)
{
if (data[leftptr] <= data[rightptr])
{
temp[tempptr++] = data[leftptr++];
}
else
{
count += middle - leftptr + 1;
temp[tempptr++] = data[rightptr++];
}
}
while (leftptr <= middle)
{
temp[tempptr++] = data[leftptr++];
}
while (rightptr <= tail)
{
temp[tempptr++] = data[rightptr++];
}
for (int i = head;i <= tail;i++)
{
data[i] = temp[i];
}
return;
}