分享

树状数组和归并排序求逆序数

 X的世界 2012-09-25

树状数组,具体的说是 离散化+树状数组。这也是学习树状数组的第一题.

算法的大体流程就是:

1.先对输入的数组离散化,使得各个元素比较接近,而不是离散的,

2.接着,运用树状数组的标准操作来累计数组的逆序数。

算法详细解释:

1.解释为什么要有离散的这么一个过程?

    刚开始以为999.999.999这么一个数字,对于int存储类型来说是足够了。

    还有只有500000个数字,何必要离散化呢?

    刚开始一直想不通,后来明白了,后面在运用树状数组操作的时候,

    用到的树状数组C[i]是建立在一个有点像位存储的数组的基础之上的,

    不是单纯的建立在输入数组之上。

    比如输入一个9 1 0 5 4,那么C[i]树状数组的建立是在,

    下标 0 1 2 3 4 5 6 7 8 9

    数组 1 1 0 0 1 1 0 0 0 1

    现在由于999999999这个数字相对于500000这个数字来说是很大的,

    所以如果用数组位存储的话,那么需要999999999的空间来存储输入的数据。

    这样是很浪费空间的,题目也是不允许的,所以这里想通过离散化操作,

    使得离散化的结果可以更加的密集。

2. 怎么对这个输入的数组进行离散操作?

   离散化是一种常用的技巧,有时数据范围太大,可以用来放缩到我们能处理的范围;

   因为其中需排序的数的范围0---999 999 999;显然数组不肯能这么大;

   而N的最大范围是500 000;故给出的数一定可以与1.。。。N建立一个一一映射;

   ①当然用map可以建立,效率可能低点;

   ②这里用一个结构体

   struct Node

   {

      int v,ord;

   }p[510000];和一个数组a[510000];

   其中v就是原输入的值,ord是下标;然后对结构体按v从小到大排序;

   此时,v和结构体的下标就是一个一一对应关系,而且满足原来的大小关系;

   for(i=1;i<=N;i++) a[p[i].ord]=i;

   然后a数组就存储了原来所有的大小信息;

   比如 9 1 0 5 4 ------- 离散后aa数组就是 5 2 1 4 3;

   具体的过程可以自己用笔写写就好了。

3. 离散之后,怎么使用离散后的结果数组来进行树状数组操作,计算出逆序数?

    如果数据不是很大, 可以一个个插入到树状数组中,

    每插入一个数, 统计比他小的数的个数,

    对应的逆序为 i- getsum( aa[i] ),

    其中 i 为当前已经插入的数的个数,

    getsum( aa[i] )为比 aa[i] 小的数的个数,

    i- sum( aa[i] ) 即比 aa[i] 大的个数, 即逆序的个数

    但如果数据比较大,就必须采用离散化方法

    假设输入的数组是9 1 0 5 4, 离散后的结果aa[] = {5,2,1,4,3};

在离散结果中间结果的基础上,那么其计算逆序数的过程是这么一个过程。

1,输入5,   调用upDate(5, 1),把第5位设置为1

1 2 3 4 5

0 0 0 0 1

计算1-5上比5小的数字存在么? 这里用到了树状数组的getSum(5) = 1操作,

现在用输入的下标1 - getSum(5) = 0 就可以得到对于5的逆序数为0。

2. 输入2, 调用upDate(2, 1),把第2位设置为1

1 2 3 4 5

0 1 0 0 1

计算1-2上比2小的数字存在么? 这里用到了树状数组的getSum(2) = 1操作,

现在用输入的下标2 - getSum(2) = 1 就可以得到对于2的逆序数为1。

3. 输入1, 调用upDate(1, 1),把第1位设置为1

1 2 3 4 5

1 1 0 0 1

计算1-1上比1小的数字存在么? 这里用到了树状数组的getSum(1) = 1操作,

现在用输入的下标 3 - getSum(1) = 2 就可以得到对于1的逆序数为2。

4. 输入4, 调用upDate(4, 1),把第5位设置为1

1 2 3 4 5

1 1 0 1 1

计算1-4上比4小的数字存在么? 这里用到了树状数组的getSum(4) = 3操作,

现在用输入的下标4 - getSum(4) = 1 就可以得到对于4的逆序数为1。

5. 输入3, 调用upDate(3, 1),把第3位设置为1

1 2 3 4 5

1 1 1 1 1

计算1-3上比3小的数字存在么? 这里用到了树状数组的getSum(3) = 3操作,

现在用输入的下标5 - getSum(3) = 2 就可以得到对于3的逆序数为2。

6. 0+1+2+1+2 = 6 这就是最后的逆序数

分析一下时间复杂度,首先用到快速排序,时间复杂度为O(NlogN),

后面是循环插入每一个数字,每次插入一个数字,分别调用一次upData()和getSum()

外循环N, upData()和getSum()时间O(logN) => 时间复杂度还是O(NlogN).

最后总的还是O(NlogN).

 


 

poj 2299 :

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 26864   Accepted: 9642

Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence 
9 1 0 5 4 ,

Ultra-QuickSort produces the output 
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

Source

 

代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string.h>
using namespace std;
  
const int maxn=500005;
int n;
int aa[maxn]; //离散化后的数组
int c[maxn];    //树状数组
  
struct Node{
   int v;
   int order;
}in[maxn];
  
int lowbit(int x)
{
    return x&(-x);
}
  
void update(int t,int value)
{
    int i;
    for(i=t;i<=n;i+=lowbit(i))
    {
        c[i]+=value;
    }
}
  
int getsum(int x)
{
    int i;
    int temp=0;
    for(i=x;i>=1;i-=lowbit(i))
    {
        temp+=c[i];
    }
    return temp;
}
  
bool cmp(Node a ,Node b)
{
    return a.v<b.v;
}
  
int main()
{
    int i,j;
    while(scanf("%d",&n)==1 && n)
    {
        //离散化
        for(i=1;i<=n;i++)
        {
            scanf("%d",&in[i].v);
            in[i].order=i;
        }
        sort(in+1,in+n+1,cmp);
        for(i=1;i<=n;i++) aa[in[i].order]=i;
        //树状数组求逆序
        memset(c,0,sizeof(c));
        long long ans=0;
        for(i=1;i<=n;i++)
        {
            update(aa[i],1);
            ans+=i-getsum(aa[i]);
        }
        cout<<ans<<endl;
    }
    return 0;
}

  利用归并排序求逆序数对的问题

 对于一个给定的数组中要去求其中逆序数对的个数,可以通过简单的两层for循环去逐个便利每一个数对,这样的思想是很容易就可以想到的,但是其算法的复杂度确是O(n^2),为了降低算法的复杂度可以试着用divide&conquer思想去考虑这个问题。

  对于一个数组{5,3,7,4,6,2,1,8},如果我们以中间(或者左中)为界限将其分成两个数组,只要知道这两个数组中的逆序对数和两边的数所组成的逆序对数就是它所有的逆序对数了。而数组划分的递归结束点在两个数组都只有一个元素的时候,因此两数组中的逆序对数可以通过递归求得。要去求分裂的两数组中的逆序对数可以这样去做:先将两数组按升序排序,若前一个数组的第一个元素比后一个的大,则说明前一组的后面所有都要比后一组的第一个元素大,这样将较小的第一个元素去掉后,继续比较两个数组的第一个元素可以把所有的逆序对找到。

 

下面是该算法的JAVA实现:

import java.util.*;
public class CountInversedNumbers{
  public static int count=0;          //记录逆序对个数;
  public void  sort_count(int []L){
    int n=L.length;                     
    int a=(int)(n/2+0.5);                
    int b=(int)(n/2);
    int A[]=new int[a];
    int B[]=new int[b];
    for (int i=0;i< a;i++) 
      A[i]=L[i];
    for (int j=0;j< b;j++) 
      B[j]=L[j+a];   //把单个数组划分成两个数组;
    if(a>1&&b>1) {
       sort_count(A);
       sort_count(B);  //递归的划分数组;
      }
    Arrays.sort(A);                              
    Arrays.sort(B);   //将数组排序;
    merge_count(A,B);
 }
public void merge_count(int []M, int[]N){  //求被划分的两个数组中元素组成的逆序对;
  int c=M.length;
  int d=N.length; 
  while(c>0&&d>0){
    if(M[0]>N[0]) {
      this.count=this.count+c;
      for(int i=0;i< d-1;i++) 
        N[i]=N[i+1];
      d--;
    } else{
      for(int j=0;j< c-1;j++) 
        M[j]=M[j+1];
      c--;
    }
  }
 }
    public static void main(String[] args){
      int K[]={6,2,3,5,7,1,4,8};
      CountInversedNumbers a=new CountInversedNumbers();
      a.sort_count(K);
      System.out.println(a.count);    //输出结果是11;
    }
}   
C++语言实现
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<fstream>
#include<iterator>
using namespace std;
const int inf = 2147483647;
int count = 0;

//get the index of the first element larger than val on [beg, end)
int upperbound(int *ia, int beg, int end, int val)
{
if (beg + 1 == end) return ia[beg] > val ? beg : -1;
int mid = beg + (end - beg) / 2;
if (ia[mid - 1] <= val)
return upperbound(ia, mid, end, val);
return upperbound(ia, beg, mid, val);
}

void merge(int *ia, int p, int q, int r)
{
for (int i = p, j = q + 1; j <= r; ++j)
if ((i = upperbound(ia, i, q + 1, ia[j])) != -1)
count += q - i + 1;
else
break;
int n1 = q - p + 1, n2 = r - q;
int *left = new int[n1 + 1], *right = new int[n2 + 1];
for (int i = 0; i != n1; ++i)
left[i] = ia[p + i];
for (int i = 0; i != n2; ++i)
right[i] = ia[q + i + 1];
left[n1] = inf;
right[n2] = inf;
int i = 0, j = 0, k = p;
while (k <= r)
if (left[i] <= right[j])
ia[k++] = left[i++];
else
ia[k++] = right[j++];
delete [] left;
delete [] right;
}


void inversionCount(int *ia, int p, int r)
{
if (p < r) {
int q = (p + r) / 2;
inversionCount(ia, p, q);
inversionCount(ia, q + 1, r);
merge(ia, p, q, r);
}
}

int _tmain(int argc, _TCHAR* argv[])
{
ifstream cin("a.txt");
for (int n; cin >> n && n; ) {
int *ia = new int[n];
for (int i = 0; i != n && cin >> ia[i]; ++i);
inversionCount(ia, 0, n - 1);
cout << count << endl;
count = 0;
delete [] ia;
}
return 0;
}
http://www.cnblogs.com/justforgl/archive/2012/07/27/2612364.html

归并排序

  直接计数法虽然简单直观,但是其时间复杂度是 O(n^2)。一个更快(但稍复杂)的计算方法是在归并排序的同时计算逆序数。下面这个 C++ 编写的例子演示了计算方法。函数 mergeSort() 返回序列的逆序数。
  int is1[n],is2[n];// is1为原数组,is2为临时数组,n为个人定义的长度
  long mergeSort(int a,int b)// 下标,例如数组int is[5],全部排序的调用为mergeSort(0,4)
  {
  if(a<b)
  {
  int mid=(a+b)/2;
  long count=0;
  count+=mergeSort(a,mid);
  count+=mergeSort(mid+1,b);
  count+=merge(a,mid,b);
  return count;
  }
  return 0;
  }
  long merge(int low,int mid,int high)
  {
  int i=low,j=mid+1,k=low;
  long count=0;
  while(i<=mid&&j<=high)
  if(is1[i]<=is1[j])// 此处为稳定排序的关键,不能用小于
  is2[k++]=is1[i++];
  else
  {
  is2[k++]=is1[j++];
  count+=j-k;// 每当后段的数组元素提前时,记录提前的距离
  }
  while(i<=mid)
  is2[k++]=is1[i++];
  while(j<=high)
  is2[k++]=is1[j++];
  for(i=low;i<=high;i++)// 写回原数组
  is1[i]=is2[i];
  return count;
  }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多