forked from himanshu010/dsa-programming-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinversion count.cpp
More file actions
119 lines (99 loc) · 2.01 KB
/
Copy pathinversion count.cpp
File metadata and controls
119 lines (99 loc) · 2.01 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
*-----------------------------------------------------------*
| AUTHOR: Himanshu Aswal |
| ( website: himanshuaswal.com ) |
*-----------------------------------------------------------*
*/
#include <bits/stdc++.h>
#define moduli 998244353
#define int long long int
#define ld long double
#define F first
#define S second
#define P pair<int, int>
#define pb push_back
#define vi vector<int>
#define vvi vector<vector<int>>
#define vb vector<bool>
#define um unordered_map
using namespace std;
const int N = 100005;
int cross_inversions_after_merging(int *a, int s, int e)
{
if (s == e)
{
return 0;
}
int mid = (s + e) / 2;
int i = s;
int j = mid + 1;
int k = s;
int cnt = 0;
int temp[N];
while (i <= mid and j <= e)
{
if (a[i] <= a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k++] = a[j++];
cnt += mid - i + 1;
}
}
while (i <= mid)
{
temp[k++] = a[i++];
}
while (j <= e)
{
temp[k++] = a[j++];
}
for (int i = s; i <= e; ++i)
{
a[i] = temp[i];
}
return cnt;
}
int inversion_count(int *a, int s, int e)
{
if (s == e)
{
return 0;
}
int mid = (s + e) / 2;
int x = inversion_count(a, s, mid);
int y = inversion_count(a, mid + 1, e);
int z = cross_inversions_after_merging(a, s, e);
return x + y + z;
}
void solve(int tc)
{
int i, j, k, n, m, ans = 0, cnt = 0, sum = 0;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
cout << inversion_count(a, 0, n - 1);
}
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// int t;cin>>t;while(t--)
{
int tc = 1;
solve(tc);
tc++;
}
}