forked from rene-d/hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion-sort.cpp
61 lines (50 loc) · 912 Bytes
/
insertion-sort.cpp
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
// Insertion Sort Advanced Analysis
// How many shifts will it take Insertion Sort to sort an array?
//
// https://www.hackerrank.com/challenges/insertion-sort/problem
//
#include <iostream>
using namespace std;
const int N = 10000000;
int cnt[N + 1];
void add(int v)
{
while (v <= N)
{
cnt[v]++;
v += v & -v;
}
}
int get(int v)
{
int sum = 0;
while (v)
{
sum += cnt[v];
v -= v & -v;
}
return sum;
}
int main()
{
int T;
cin >> T;
while (T--)
{
int n;
cin >> n;
long long changes = 0;
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
int cnt_larger = get(N) - get(a);
changes += cnt_larger;
add(a);
}
cout << changes << endl;
for (int i = 0; i <= N; i++)
cnt[i] = 0;
}
return 0;
}