View Code of Problem 126

#include<bits/stdc++.h>
using namespace std;
struct node
{
	string str;
	int id, cnt;
}a[105];
bool cmp(node n1, node n2) {
	if (n1.cnt != n2.cnt)
		return n1.cnt < n2.cnt;
	return n1.id < n2.id;
}
int n, m;
int main() {
	while (cin >> n >> m) {
		for (int i = 1; i <= m; i++) {
			cin >> a[i].str;
			a[i].id = i;
			a[i].cnt = 0;
		}
		
		for (int k = 1; k <= m; k++) {
			string t = a[k].str;
			for (int i = 0; i < n; i++) {
				int flag = 1;
				for (int j = 0; j < n - i; j++) {
					if (t[j] > t[j + 1]) {
						swap(t[j], t[j + 1]);
						a[k].cnt++;
						flag = 0;
					}
				}
				if (flag)
					break;
			}
		}
		
		sort(a + 1, a + 1 + m, cmp);

		for (int i = 1; i <= m; i++)
			cout << a[i].str << endl;
	}
	return 0;
}

Double click to view unformatted code.


Back to problem 126