find inverse pair

The reverse order pair is the exchange of the least number of adjacent elements exchanged

Reverse ordinal

 51Node - 1019 

In a permutation, a pair of numbers is said to be in reverse order if they are in reverse order of magnitude, i.e. the preceding number is greater than the latter. The total number of inversions in a permutation is called the number of inversions of the permutation.

 
For example, in 2 4 3 1, 2 1, 4 3, 4 1, 3 1 are the reverse order, and the reverse order number is 4. Given a sequence of integers, find the inverse of the sequence.

Input Line 1: N, N is the length of the sequence (n <= 50000) 
Line 2 - N + 1: Elements in the sequence (0 <= A i i <= 10^9) Output Output the inverse number Sample Input

4
2
4
3
1

Sample Output

4

merge sort

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
const int N=100005;
int w[N],sum[N],n;
struct T
{
    int xn
} a[N],T[N];
void la ( int l, int r)
{
    if(r-l==1)return;
    int m=l+r>>1,tm=l+r>>1,tl=l,i=l;
    la(l,m),la(m,r);
    while(tl<m||tm<r)
    {
        if(tm>=r||(tl<m&&a[tl].x<=a[tm].x))
            T[i++]=a[tl++],T[i-1].num+=tm-m;
        else
            T[i++]=a[tm++];
    }
    for(int i=l; i<r; i++)a[i]=T[i];
}
intmain ()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        scanf("%d",&a[i].x),a[i].num=0;
    la( 0 ,n);
    __int64 ans=0;
    for(int i=0; i<n; i++)ans+=a[i].num;
    printf("%I64d",ans);
    return 0;
}

sort+find

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
const int N=100005;
int w[N],n;
long long la(int l,int r)
{
    if(r-l==1)return 0;
    int m=l+r>>1,s=la(l,m)+la(m,r),t;
    for(int i=l; i<m; ++i)
        s+=lower_bound(w+m,w+r,w[i])-w-m;
    sort(w+l,w+r);
    return s;
}
intmain ()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        scanf("%d",&w[i]);
    cout<<la(0,n);
    return 0;
}

tree array

#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 500005;
struct Node
{
    int val;
    int pos;
    friend bool operator <(Node a,Node b)
    {
        return a.val < b.val;
    }
};
Node node [N];
int c[N], hash[N], n;
int lowbit(int x)
{
    return x & (-x);
}

void update(int x)
{
    while (x <= n)
    {
        c[x] += 1;
        x += lowbit(x);
    }
}

int getsum(int x)
{
    int sum = 0;
    while (x > 0)
    {
        sum += c[x];
        x -= lowbit(x);
    }
    return sum;
}

intmain ()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
    {
        scanf("%d", &node[i].val);
        node[i].pos = i;
    }
    sort(node + 1, node + n + 1);
    for (int i = 1; i <= n; ++i) 
        hash[node[i].pos] = i;
    int  ans = 0;
    for (int i = 1; i <= n; ++i)
    {
        update(hash[i]);
        ans += i - getsum(hash[i]);
    }
    printf("%d\n", ans);
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325158117&siteId=291194637