# 归并排序+归并排序求逆序对（例题P1908）

## 归并排序代码

```#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<string>
#include<fstream>
#include<vector>
#include<stack>
#include <map>
#include <iomanip>

#define bug cout << "**********" << endl
#define show(x, y) cout<<"["<<x<<","<<y<<"] "
#define LOCAL = 1;
using namespace std;
typedef long long ll;
const int inf = 1e9 + 7;
const ll mod = 1e9 + 7;
const int Max = 5e5 + 10;

int n;
ll sum;
int alt[Max];

void merge(int a[], int l, int r)
{
for(int i= l; i <= r; i ++)
{
alt[i] = a[i];
}
int mid = (l + r) >> 1;
int i = l, j = mid + 1;
for (int pos = l; pos <= r; pos++)
{
if (i == mid + 1)
{
a[pos] = alt[j];
j++;
}
else if (j == r + 1)
{
a[pos] = alt[i];
i++;
}
else if (alt[i] > alt[j])
{
a[pos] = alt[j];
j++;
}
else
{
a[pos] = alt[i];
i++;
}
}
}

void merge_sort(int a[], int l, int r)
{
if (l == r)
return;
int mid = (l + r) >> 1;
merge_sort(a, l, mid);
merge_sort(a, mid + 1, r);
merge(a, l, r);
}

int a[Max];

int main()
{
#ifdef LOCAL
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
sum = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", a + i);
merge_sort(a, 0, n - 1);
for(int i = 0 ;i < n ;i ++)
printf("%d%c",a[i],i == n-1?‘\n‘:‘ ‘);
return 0;
}```
View Code

## 代码区

(点击此处查看模板题）

```#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<string>
#include<fstream>
#include<vector>
#include<stack>
#include <map>
#include <iomanip>

#define bug cout << "**********" << endl
#define show(x, y) cout<<"["<<x<<","<<y<<"] "
#define LOCAL = 1;
using namespace std;
typedef long long ll;
const int inf = 1e9 + 7;
const ll mod = 1e9 + 7;
const int Max = 5e5 + 10;

int n;
ll sum;
int alt[Max];

void merge(int a[], int l, int r)
{
for(int i= l; i <= r; i ++)
{
alt[i] = a[i];
}
int mid = (l + r) >> 1;
int i = l, j = mid + 1;
for (int pos = l; pos <= r; pos++)
{
if (i == mid + 1)
{
a[pos] = alt[j];
j++;
}
else if (j == r + 1)
{
a[pos] = alt[i];
i++;
}
else if (alt[i] > alt[j])
{
a[pos] = alt[j];
j++;
sum += mid - i + 1;        //i及其此后的都可以和a[j]形成逆序对
}
else
{
a[pos] = alt[i];
i++;
}
}
}

void merge_sort(int a[], int l, int r)
{
if (l == r)
return;
int mid = (l + r) >> 1;
merge_sort(a, l, mid);
merge_sort(a, mid + 1, r);
merge(a, l, r);
}

int a[Max];

int main()
{
#ifdef LOCAL
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
sum = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", a + i);
merge_sort(a, 0, n - 1);
printf("%lld\n", sum);
return 0;
}```
View Code

(0)
(0)