简单的题目,如题:找出字符串中的反转次数。按反转次数从小到大输出。
反转次数,就是字符串中的每一个跟它后面的每一个字符比较,比后面的大的,次数+1.
下面的是AC的代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
class data
{
public:
char str[55];
int count;
};
data Dd[102];
int cmp(data &a, data &b)
{
return a.count < b.count;
}
int main()
{
// freopen("data.txt", "r", stdin);
int m, n;
char temp[55];
int i, j, k;
cin >> m >> n;
for(i = 0; i < n; i++)
{
cin >> temp;
int c = 0;
for(j = 0; j < m - 1; j++)
{
for(k = j + 1; k < m; k++)
{
if(temp[j] > temp[k])
c++;
}
}
Dd[i].count = c;
strcpy(Dd[i].str, temp);
}
sort(Dd, Dd + n, cmp);
for(i = 0; i < n; i++)
cout << Dd[i].str << endl;
return 0;
}
运用类,在输入的时候,算出反转次数。
排序一下就OK了。