关键是统计字符串的逆序然后根据逆序数排序输出字符串。
其实也是比较基本的,但网上很多统计逆序是O(n*n)的解法,可以采用分治法统计逆序,过程类似于二路归并排序,时间复杂度是O(n*lgn)。
对逆序的数目进行排序自己写了个快排。。就当是复习一下。
#include<iostream>
#include<string>
using namespace std;
struct DNA{
string s;
int revers;
};
int reversion;
void merge(string &s,int beg,int mid,int end){
int left = mid-beg+1;
int right= end-mid;
char *tempA = (char *)malloc(left);
char *tempB = (char *)malloc(right);
int i,j;
for(i = 0; i<left; i++){
tempA[i] = s[beg+i];
}
for(j = 0; j<right;j++){
tempB[j] = s[mid+1+j];
}
i=0,j=0;
int k = beg;
while(i<left && j <right){
if(tempA[i] <= tempB[j]){
s[k] = tempA[i];
++i;
}
else{
reversion += left-i;
s[k] = tempB[j];
++j;
}
++k;
}
while(i<left){
s[k] = tempA[i++];
++k;
}
while(j<right){
s[k] = tempB[j++];
++k;
}
//刚开始忘记free了结果内存超过要求
free(tempA);
free(tempB);
}
void mergesort(string &s,int beg,int end){
if(beg <end ){
int mid = (beg+end)>>1;
mergesort(s,beg,mid);
mergesort(s,mid+1,end);
merge(s,beg,mid,end);
}
}
void qsort_dna(DNA dna[],int beg,int end){
if(beg >= end)
return;
int i =beg,j = end+1;
DNA axis = dna[beg];
DNA temp;
while( i< j){
do{
++i;
}while(dna[i].revers <= axis.revers && i < j);
do{
--j;
}while(dna[j].revers >= axis.revers && j> beg);
//上面的j>beg是必须的。。比如元素全相等的情况没有限制会出错
if( i < j){
temp = dna[i];
dna[i] = dna[j];
dna[j] = temp;
}
}
temp = dna[beg];
dna[beg] = dna[j];
dna[j] = temp;
qsort_dna(dna,beg,j-1);
qsort_dna(dna,j+1,end);
}
int main()
{
int length,n;
cin>>length>>n;
int order =0;
DNA *dna = new DNA[n];
while(order <n){
string s;
cin>>s;
dna[order].s = s;
reversion =0;
mergesort(s,0,s.length()-1);
dna[order].revers= reversion;
order++;
}
qsort_dna(dna,0,n-1);
for(int i= 0;i <n;++i){
cout<<dna[i].s<<endl;
}
delete [] dna;
return 0;
}