标签:
1 #include<cstdio> 2 #include<cstring> 3 #include<malloc.h> 4 #include<algorithm> 5 using namespace std; 6 7 int ans; 8 9 struct str 10 { 11 char s[105]; 12 char sort_s[105]; 13 int Num; 14 }; 15 16 bool cmp(struct str a,struct str b) 17 { 18 return a.Num<b.Num; 19 } 20 21 void MergeArray(char a[],int L,int Mid,int R,char temp[]) 22 { 23 int k=0; 24 int i=L,j=Mid+1; 25 int m=Mid,n=R; 26 while(i<=m&&j<=n) 27 { 28 if(a[i]<=a[j]) 29 temp[k++]=a[i++]; 30 else 31 { 32 temp[k++]=a[j++]; 33 ans+=m-i+1; 34 } 35 } 36 while(i<=m) 37 temp[k++]=a[i++]; 38 while(j<=n) 39 temp[k++]=a[j++]; 40 for(i=0;i<k;i++) 41 a[L+i]=temp[i]; 42 } 43 44 void MergeSort(char a[],int L,int R,char temp[]) 45 { 46 if(L<R) 47 { 48 int Mid=(L+R)/2; 49 MergeSort(a,L,Mid,temp); 50 MergeSort(a,Mid+1,R,temp); 51 MergeArray(a,L,Mid,R,temp); 52 } 53 } 54 55 int main() 56 { 57 struct str S[55]; 58 int i,m,n,t; 59 scanf("%d",&t); 60 while(t--) 61 { 62 scanf("%d%d",&m,&n); 63 for(i=0;i<n;i++) 64 scanf("%s",S[i].s); 65 for(i=0;i<n;i++) 66 { 67 ans=0; 68 int len=strlen(S[i].s); 69 strcpy(S[i].sort_s,S[i].s); 70 char *p=(char*)malloc(sizeof(char)*(len+1)); 71 MergeSort(S[i].sort_s,0,len-1,p); 72 S[i].Num=ans; 73 free(p); 74 } 75 sort(S,S+n,cmp); 76 for(i=0;i<n;i++) 77 printf("%s\n",S[i].s); 78 } 79 return 0; 80 }
标签:
原文地址:http://www.cnblogs.com/homura/p/4677890.html