这个题的大体意思是要求按照字符串中字符排列的逆序数对多个字符串进行排列,若两个字符串的逆序数相同,则按照输入顺序输出。
思路:将字符串和它的逆序数组成一个结构体,按照逆序数对结构体排序再输出即可。
代码:
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
#include<iostream>
#include<string>
using namespace std;
struct sorted
{
string b;
int c;
};
struct sorted a[101];
int main()
{
int i,j,k,l,m,n,x,y,t;
struct sorted o;
cin>>t;
for (k=1;k<=t;k++)
{
cin>>n>>m;
for (i=1;i<=m;i++)
{
cin>>a[i].b;
for (j=0,x=0;j<n;j++)
for (l=j+1;l<n;l++)
{
if (a[i].b[j]>a[i].b[l])
x+=1;
}
a[i].c=x;
}
for (i=m;i>=2;i--)
for (j=1;j+1<=i;j++)
{
if (a[j].c>a[j+1].c)
{
o=a[j];
a[j]=a[j+1];
a[j+1]=o;
}
}
for (i=1;i<=m;i++)
{
cout<<a[i].b<<endl;
}
if (k!=t)cout<<endl;
}
}