-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmurder.cpp
More file actions
80 lines (55 loc) · 1.11 KB
/
murder.cpp
File metadata and controls
80 lines (55 loc) · 1.11 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<bits/stdc++.h>
using namespace std;
long merge(int *a, int start, int mid, int end){
int i = start, j = mid, k = 0;
long sum = 0;
int *temp = new int[end - start + 1];
while(i < mid && j <= end){
if(a[i] < a[j]){
temp[k++] = a[i++];
sum += (end - j + 1) * a[i];
}
else{
temp[k++] = a[j++];
}
}
while(i < mid){
temp[k++] = a[i++];
}
while(j <= end){
temp[k++] = a[j++];
}
for(int i = start, k = 0; i <= end; i++, k++){
a[i] = temp[k];
}
delete [] temp;
return sum;
}
long mergeSort(int *a, int start, int end){
long sum = 0;
if(start < end){
int mid = (start + end)/2;
long leftAns = mergeSort(a, start, mid);
long rightAns = mergeSort(a, mid+1, end);
long currentAns = merge(a, start, mid+1, end);
cout << leftAns << " " << rightAns << " " << currentAns << endl;
sum = leftAns + rightAns + currentAns;
}
return sum;
}
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int *arr = new int[n];
for(int i = 0; i < n; i++){
cin >> arr[i];
}
long ans = mergeSort(arr, 0, n-1);
cout << ans << endl;
delete [] arr;
}
return 0;
}