10分求助(归并排序加map离散化)
查看原帖
10分求助(归并排序加map离散化)
394488
tzyt楼主2021/7/29 19:41
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e8 - 3;
long long a[100001], b[100001],n,orig_a[1000001],orig_b[100001],sorting[100001],temp[100001];
long long ans = 0;
map<long long, long long> map_a, map_b;
void input(){
    scanf("%lld", &n);
    for (int i = 1; i <= n;i++){
        scanf("%lld", &a[i]);
        orig_a[i] = a[i];
    }
    for (int i = 1; i <= n;i++){
        scanf("%lld", &b[i]);
        orig_b[i] = b[i];
    }
}

void mapping(){
    sort(a + 1, a + 1 + n);
    sort(b + 1, b + 1 + n);
    for (int i = 1; i <= n;i++){
        map_a[a[i]] = i;    //离散化(a[i]是a这组火柴中第i小的)
        map_b[b[i]] = i;
    }
    for (int i = 1; i <= n;i++){
        orig_a[i] = map_a[orig_a[i]];
        orig_b[i] = map_b[orig_b[i]];   //把离散化后的数据存入orig数组
    }
    for (int i = 1; i <= n;i++){
        sorting[orig_a[i]] = orig_b[i];
    }
}

void merge(int l,int r){//归并排序
    if(l==r){
        return;
    }
    int mid = (l + r) / 2;
    merge(l, mid);
    merge(mid + 1, r);
    int seg_l_begin = l, seg_r_begin = mid+1, temp_begin = l;//把l~r分成两段,begin变量为两段和临时数组的指针
    while(seg_l_begin<=mid&&seg_r_begin<=r){
        if(sorting[seg_l_begin]<=sorting[seg_r_begin]){//未产生逆序对
            temp[temp_begin] = sorting[seg_l_begin];
            temp_begin++;
            seg_l_begin++;
        }
        else{//产生逆序对
            temp[temp_begin] = sorting[seg_r_begin];
            temp_begin++;
            seg_r_begin++;
            ans += (mid - (seg_l_begin - 1))%MOD;//记录产生的逆序对数量
        }
    }
    while(seg_l_begin<=mid){
        temp[temp_begin] = sorting[seg_l_begin];
        temp_begin++;
        seg_l_begin++;
    }
    while(seg_r_begin<=r){
        temp[temp_begin] = sorting[seg_r_begin];
        temp_begin++;
        seg_r_begin++;
    }
    for (int i = l; i <= r;i++){
        sorting[i] = temp[i];
    }
}

int main(){
    input();
    mapping();
    merge(1,n);
    printf("%lld\n", ans%MOD);
    system("pause");
    return 0;
}
2021/7/29 19:41
加载中...