求逆序数对(归并排序)

本文深入浅出地讲解了归并排序算法,并提供了C++语言的具体实现。通过实例代码,详细解决了计算排列中逆序数对的问题,为读者提供了一套高效且易于理解的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

推荐一个今天收获的博客,该博客将归并排序解释地相当清楚,并且有C++语言的实现方法

http://wangkuiwu.github.io/2014/04/28/merge-sort/


主要是解决逆序数对


如题


1007. Inversion Number


题目描述
There is a permutation P with n integers from 1 to n. You have to calculate its inversion number, which is the number of pairs of Pi and Pj satisfying the following conditions: i<j and Pi>Pj. 

输入格式

The input may contain several test cases.

In each test case, the first line contains a positive integer n (n<=100000) indicating the number of elements in P. The following n lines contain n integers making the permutation P.

Input is terminated by EOF.


输出格式

 For each test case, output a line containing the inversion number.


样例输入
 将样例输入复制到剪贴板
5
3
4
1
5
2
样例输出
5

Problem Source: 期末模拟题C


// Problem#: 13510
// Submission#: 3503240
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
const int maxn = 1000;
long long ans = 0;
int A[1000005];
/* 排列两个有序的表 */

void merge(int a[], int start, int mid, int end)
{
    int temp[end-start-1];
    int i = start;          // 第1个有序区的索引
    int j = mid + 1;        // 第2个有序区的索引
    int k = 0;              // 临时区域的索引
    while(i <= mid && j <= end)
    {
        if(a[i] <= a[j])
            temp[k++] = a[i++];
        else
        {
            temp[k++] = a[j++];
            ans += mid - i + 1;
        }
    }
    while(i <= mid)
        temp[k++] = a[i++];
    while(j <= end)
        temp[k++] = a[j++];
    // 将排序后的元素,全部都整合到数组a中。
    for (i = 0; i < k; i++)
        a[start + i] = temp[i];
}

/*
 * 归并排序(从上往下)
 *
 * 参数说明:
 *     a -- 待排序的数组
 *     start -- 数组的起始地址
 *     endi -- 数组的结束地址
 */

 void merge_sort_up2down(int a[], int start, int end)
 {
    if(a == NULL || start >= end)
        return;
    int mid = (start + end) / 2;
    merge_sort_up2down(a, start, mid);
    merge_sort_up2down(a, mid+1, end);
    merge(a, start, mid, end);
 }

int main(){
    int n;
    while (scanf("%d",&n)!=EOF)
    {
        ans = 0;
        int i;
        for (i=0;i



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值