逆序对问题:
在树状数组的应用中已经对逆序对问题进行了一次解答。
下面说明另一种经典解法:归并排序
#include <iostream>
#include <stdio.h>
using namespace std;
int num[1005];
int temp[1005];
int ans;
int merge_sort(int s, int e)
{
if(s == e) // 返回
return 0;
int m = (s+e)>>1; // 右移一位,相当于除2
//cout<<m;
//getchar();
merge_sort(s,m);
merge_sort(m+1,e);
int cnt = 0;
int i,j;
for( i = s, j = m+1; i<=m && j <= e; )
{
if( num[i] > num[j] )
{
temp[cnt++] = num[j];
j++;
ans += (m-i+1); //更新逆序对的数量
}
else
{
temp[cnt++] = num[i];
i++;
}
}
while( i<= m)
{
temp[cnt++] = num[i++];
}
while(j<= e)
temp[cnt++] = num[j++];
for(int c = 0; c<cnt ; c++)
num[s+c] = temp[c]; //重新幅值回来,得到有序的数组
}
int main(int arg, char** argv)
{
int n_num;
cout<<"输入数字的个数:";
cin>>n_num;
if(n_num<1)
{
cout<< "wrong input !";
return -1;
}
ans = 0;
cout<< "请输入"<<n_num<<"个数:";
for(int i = 1 ; i<= n_num ; i++)
{
cin>>num[i];
}
merge_sort(1,n_num);
for(int i = 1; i<=n_num; i++)
cout<< num[i]<<" ";
cout<<endl<< "逆序对的数量:"<<ans;
return 0;
}
做了一个搬运工,手打的代码,加深映像!!!
TJU-26E
2016-5-30