POJ 1256

//#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#define N_MAX 14
#define M_MAX 58
int T;
int len;
char buf[N_MAX];
int ret[N_MAX];
int aa[M_MAX]; //字符=>数字的映射
int bb[M_MAX]; //数字=>字符的映射
char *in = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";

void init() // 映射
{
	int len = strlen(in);
	int val = 0;
	for (int i = 0; i < len; i++) {
		int idx = in[i] - 'A';
		bb[val] = in[i];
		aa[idx] = val++;
	}
}

void qsort(int *a, int begin, int end)
{
	if (begin >= end) return;
	int l = begin, r = end, k = a[l];
	while (l < r) {
		while (l < r && k <= a[r]) r--;
		while (l < r && k >= a[l]) l++;
		if (l < r) {
			int tmp = a[l];
			a[l] = a[r];
			a[r] = tmp;
		}
	}
	a[begin] = a[l];
	a[l] = k;
	qsort(a, begin, l - 1);
	qsort(a, l + 1, end);
}

void to_ret()
{
	for (int i = 0; i < len; i++) {
		int idx = buf[i] - 'A';
		ret[i] = aa[idx];
		//printf("%d\n", ret[i]);
	}

	qsort(ret, 0, len - 1);
}

void print_ret()
{
	for (int i = 0; i < len; i++) {
		printf("%d", ret[i]);
	}
	printf("\n");
}

void print_()
{
	for (int i = 0; i < len; i++) {
		int idx = ret[i];
		printf("%c", bb[idx]);
	}
	printf("\n");
}

int main(int argc, char* argv[])
{
	//setbuf(stdout, NULL);
	//freopen("sample_input.txt", "r", stdin);

	int T = 0;
	scanf("%d", &T);
	init();
	while (T--) {
		memset(buf, 0, sizeof(char) * N_MAX);
		memset(ret, 0, sizeof(char) * N_MAX);
		scanf("%s", buf);
		//printf("buf = %s\n", buf);

		len = strlen(buf);

		to_ret();

		print_();

		while (1)
		{
			int i = len - 1;
			for (; i >= 0; i--) {
				if (ret[i] > ret[i - 1]) {
					break;
				}
			}

			if (i == 0) {
				break;
			}

			int min = 'z';
			int l = i - 1;
			int r = i;
			for (int j = i; j < len; j++) {
				if (ret[j] > ret[l] && ret[j] < min) {
					min = ret[j];
					r = j;
				}
			}

			int tmp = ret[l];
			ret[l] = ret[r];
			ret[r] = tmp;
			
			qsort(ret, i, len - 1);
			print_();
		}
	}

	return 0;
}

 

posted @ 2017-10-24 13:50  Kjing  阅读(325)  评论(0编辑  收藏  举报