备战NOIP——模板复习17

这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。

逆序数

树状数组

/*Copyright: Copyright (c) 2018
*Created on 2018-11-05 
*Author: 十甫
*Version 1.0 
*Title: 树状数组求逆序对
*Time: inf mins
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int size = 500005;
typedef long long ll;

struct num {
	int i, k;
	bool operator < (const num cmp) const {
		return k < cmp.k;
	}
} data[size];
int n;
int bit[size], ord[size];
inline int lowbit(int x) {
	return x & (-x);
}
void add(int a[], int pos, int k) {
	while(pos <= n) {
		a[pos] += k;
		pos += lowbit(pos);
	}
}
inline int query(int a[], int pos) {
	int res = 0;
	while(pos) {
		res += a[pos];
		pos -= lowbit(pos);
	}
	return res;
}

int main() {
	while(scanf("%d", &n) && n) {
		memset(bit, 0, sizeof(bit));
		memset(ord, 0, sizeof(ord));
		for(int i = 1;i <= n;i++) {
			int k;
			scanf("%d", &k);
			data[i] = (num) {i, k};
		}
		sort(data + 1, data + 1 + n);
		int cnt = 1;
		for(int i = 1;i <= n;i++) {
			if(i != 1 && data[i].k != data[i - 1].k) {
				cnt++;
			}
			ord[data[i].i] = cnt;
		}
		ll ans = 0;
		for(int i = 1;i <= n;i++) {
			add(bit, ord[i], 1);
			ans += (i - query(bit, ord[i]));
		}
		printf("%lld\n", ans);
	}
	return 0;
}

归并排序

/*Copyright: Copyright (c) 2018
*Created on 2018-11-05
*Author:  Kaizyn_洛谷题解
*Version 1.0 
*Title: 归并排序求逆序对
*Time: inf mins
*/
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int Maxn = 5e5 + 7;

int n;
long long ans;
int a[Maxn], tmp[Maxn];

void merge_sort(int l, int r) // [L, R)
{
    if(r - l <= 1) return;
    int mid = (l + r) >> 1;
    merge_sort(l,mid); // [L, Mid)
    merge_sort(mid,r); // [Mid, R)

    int i = l, j = mid, pos = l;
    while(pos < r)
    {
        if(i >= mid || j < r && a[j] < a[i] )
        {
            tmp[pos++] = a[j++];
            ans += mid - i;
        }
        else tmp[pos++] = a[i++];
    }
    memcpy(a+l,tmp+l,sizeof(int)*(r-l));
    // for(int k = l; k < r; ++k) a[k] = tmp[k];
}

int main()
{
    while( scanf("%d",&n) && n !=0 )
    {
        for(register int i = 0; i < n; ++ i) scanf("%d",a+i);
        ans = 0;
        merge_sort(0,n);
        printf("%lld\n",ans);
    }
    return 0;
}

 

posted @ 2018-11-05 07:58  十甫  阅读(86)  评论(0编辑  收藏  举报