PAT顶级(归并排序求逆序对)——1010 Lehmer Code (35 分)

1010 Lehmer Code (35 分)


解题思路:

这连续的逆序对是我没想到的,没什么好说的,比1009简单多了,1009还是变形,这个直接裸题,差点就把逆序对写题意上了,实际上就是求每个位置的逆序对有多少个,逆序对有两种,也就是ai>aj(i<j),看你是针对ai求还是针对aj求(都求就重复了),这题要做的就是针对ai求,也就是求出每个数在其后面比他小的元素数,对归并求逆序对做一点修改即可——在排序的过程中不断记录数字的原下标(建议用结构体),每次在原下标下累加答案,最后按下标输出即可。

代码:

#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define pb push_back
#define G 6.67430*1e-11
#define  rd read()
#define pi 3.1415926535
using namespace std;
const ll mod = 1e9 + 7;
const int MAXN = 30000005;
const int MAX2 = 300005;
inline ll read() {
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch>'9') {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
ll fpow(ll a, ll b)
{
    ll ans = 1;
    while (b)
    {
        if (b & 1)ans = ans * a % mod;
        b >>= 1;
        a = a * a % mod;
    }
    return ans;
}
ll gcd(ll a, ll b) { return !b ? a : gcd(b, a % b); }
ll you[200005];
ll zuo[200005];
struct ss
{
    int num;
    int pos;
}x[200005];
ll ans = 0;
void merge(ss arr[], int s, int mid, int e)
{
    vector<ss> l, r;
    for (int i = s; i <= mid; i++)
    {
        l.push_back(arr[i]);
    }
    for (int i = mid + 1; i <= e; i++)
    {
        r.push_back(arr[i]);
    }
    int lpos = 0, rpos = 0;
    while (lpos < l.size() && rpos < r.size())
    {
        if (l[lpos].num < r[rpos].num)
        {
            arr[s++] = l[lpos];
            //ans += rpos;
            you[l[lpos].pos]+= rpos;//比他小却排在它的右边
            lpos++;
        }
        else
        {
            arr[s++] = r[rpos];
            //ans += (l.size() - lpos);
            rpos++;
        }
    }
    while (lpos < l.size())
    {
        arr[s++] = l[lpos];
        //ans += rpos;
        you[l[lpos].pos] += rpos;//比他小却排在它的右边
        lpos++;
    }
    while (rpos < r.size())
    {
        arr[s++] = r[rpos];
        rpos++;
    }
}
void mergesort(ss arr[], int s, int e)
{
    if (s >= e)
    {
        return;
    }
    int mid = (s + e) / 2;
    mergesort(arr, s, mid);
    mergesort(arr,mid + 1, e);
    merge(arr, s, mid, e);
}
bool cmp(ss a, ss b)
{
    return a.pos < b.pos;
}
signed main()
{
    int n=rd;
    for (int i = 0; i < n; i++)
    {
        x[i].num = rd;
        x[i].pos = i;
    }
    mergesort(x, 0, n - 1);
    for (int i = 0; i < n; i++)
    {
        if (i)cout << ' ';
        cout << you[i];
        
    }
    return 0;
}```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值