zoukankan      html  css  js  c++  java
  • 逆序对

    树状数组求法(权值树状数组)

    (O((N + M) log M))
    对于值域较大的要离散化

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    using namespace std;
    const int MAXN = 40005;
    int init() {
    	int rv = 0, fh = 1;
    	char c = getchar();
    	while(c < '0' || c > '9') {
    		if(c == '-') fh = -1;
    		c = getchar();
    	}
    	while(c >= '0' && c <= '9') {
    		rv = (rv<<1) + (rv<<3) + c - '0';
    		c = getchar();
    	}
    	return fh * rv;
    }
    int n, dat[MAXN], id[MAXN], sub[MAXN], c[MAXN], size;
    int lowbit(const int & x){
    	return x & -x;
    }
    int query(int x) {
    	int ans = 0;
    	for( ; x; x -= lowbit(x)) ans += c[x];
    	return ans;
    }
    void add(int x, int y) {
    	for( ; x <= size; x += lowbit(x)) c[x] += y;
    }
    int main() {
    	n = init();
    	for(int i = 1; i <= n; i++) {
    		dat[i] = sub[i] = init();
    	}
    	sort(sub + 1, sub + n + 1);
    	size = unique(sub + 1, sub + n + 1) - sub - 1;
    	for(int i = 1; i <= n; i++) {
    		id[i] = lower_bound(sub + 1, sub + size + 1, dat[i]) - sub;
    	}
    	int ans = 0;
    	for(int i = n; i >= 1; i--) {
    		add(id[i], 1);
    		ans += query(id[i] - 1);
    	}
    	cout << ans << endl;
    	return 0;
    }
    

    归并排序求逆序对

    #include <iostream>
    #include <cmath>
    #include <algorithm>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;
    const int MAXN = 40005;
    int init() {
    	int rv = 0, fh = 1;
    	char c = getchar();
    	while(c < '0' || c > '9') {
    		if(c == '-') fh = -1;
    		c = getchar();
    	}
    	while(c >= '0' && c <= '9') {
    		rv = (rv<<1) + (rv<<3) + c - '0';
    		c = getchar();
    	}
    	return fh * rv;
    }
    int n, m, a[MAXN], b[MAXN], ans;
    void merge_sort(int l, int r) {
    	if(l == r) return;
    	int mid = (l + r) >> 1;
    	merge_sort(l, mid);
    	merge_sort(mid + 1, r);
    	int i = l, j = mid + 1;
    	for(int k = l; k <= r; k++) {
    		if(j > r || (i <= mid && a[i] < a[j])) b[k] = a[i++];
    		else b[k] = a[j++], ans += mid - i + 1;
    	}
    	for(int i = l; i <= r; i++) a[i] = b[i];
    }
    int main() {
    	n = init();
    	for(int i = 1; i <= n; i++) a[i] = init();
    	merge_sort(1, n);
    	//for(int i = 1;i <= n; i++) cout << a[i] << " ";
    	cout << ans << endl;
    	return 0;
    }
    
  • 相关阅读:
    hdu 5723 Abandoned country 最小生成树 期望
    OpenJ_POJ C16G Challenge Your Template 迪杰斯特拉
    OpenJ_POJ C16D Extracurricular Sports 打表找规律
    OpenJ_POJ C16B Robot Game 打表找规律
    CCCC 成都信息工程大学游记
    UVALive 6893 The Big Painting hash
    UVALive 6889 City Park 并查集
    UVALive 6888 Ricochet Robots bfs
    UVALive 6886 Golf Bot FFT
    UVALive 6885 Flowery Trails 最短路
  • 原文地址:https://www.cnblogs.com/Mr-WolframsMgcBox/p/8598893.html
Copyright © 2011-2022 走看看