2018-03-19 20:39:14 +03:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2020-05-29 23:23:24 +03:00
|
|
|
#include <string.h>
|
2018-03-19 20:39:14 +03:00
|
|
|
|
2020-04-24 03:45:45 +03:00
|
|
|
void swap(char *left, char *right)
|
|
|
|
{
|
2018-03-19 20:39:14 +03:00
|
|
|
char temp = *left;
|
|
|
|
*left = *right;
|
|
|
|
*right = temp;
|
|
|
|
}
|
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
int compare(const void *a, const void *b) { return (*(char *)a - *(char *)b); }
|
2018-03-19 20:39:14 +03:00
|
|
|
|
2020-04-24 03:45:45 +03:00
|
|
|
void PrintSortedPermutations(char *str)
|
2018-03-19 20:39:14 +03:00
|
|
|
{
|
|
|
|
int strSize = strlen(str);
|
|
|
|
qsort(str, strSize, sizeof(char), compare);
|
|
|
|
|
|
|
|
int largerPermFound = 1;
|
2020-04-24 03:45:45 +03:00
|
|
|
do
|
|
|
|
{
|
2018-03-19 20:39:14 +03:00
|
|
|
// 1. Print permutation
|
|
|
|
printf("%s\n", str);
|
|
|
|
// 2. Find rightmost char that is smaller than char to its right
|
|
|
|
int i;
|
2020-04-24 03:45:45 +03:00
|
|
|
for (i = strSize - 2; i >= 0 && str[i] >= str[i + 1]; --i)
|
|
|
|
{
|
|
|
|
}
|
2018-03-19 20:39:14 +03:00
|
|
|
|
|
|
|
// if we couldn't find one, we're finished, else we can swap
|
2020-04-24 03:45:45 +03:00
|
|
|
if (i >= 0)
|
|
|
|
{
|
2020-05-29 23:23:24 +03:00
|
|
|
// 3. find character at index j such that str[j] = min(str[k]) &&
|
|
|
|
// str[k] > str[i] for all k > i
|
2020-04-24 03:45:45 +03:00
|
|
|
int j = i + 1, k;
|
|
|
|
for (k = j; k < strSize && str[k]; k++)
|
|
|
|
{
|
2018-03-19 20:39:14 +03:00
|
|
|
if (str[k] > str[i] && str[k] < str[j])
|
|
|
|
j = k;
|
|
|
|
}
|
|
|
|
// 3. Swap chars at i and j
|
|
|
|
swap(&str[i], &str[j]);
|
|
|
|
// 4. Sort string to the right of i
|
2020-04-24 03:45:45 +03:00
|
|
|
qsort(str + i + 1, strSize - i - 1, sizeof(char), compare);
|
2018-03-19 20:39:14 +03:00
|
|
|
}
|
2020-04-24 03:45:45 +03:00
|
|
|
else
|
|
|
|
largerPermFound = 0;
|
|
|
|
} while (largerPermFound);
|
2018-03-19 20:39:14 +03:00
|
|
|
}
|
|
|
|
|
2020-04-24 03:45:45 +03:00
|
|
|
int main()
|
|
|
|
{
|
2020-06-28 22:57:00 +03:00
|
|
|
int n; // size of string
|
|
|
|
scanf("%d\n", &n);
|
|
|
|
if (n <= 0 || n >= 1000)
|
|
|
|
{
|
|
|
|
perror("Input number out of range: >0 and <1000\n");
|
|
|
|
return -1;
|
|
|
|
}
|
2020-04-24 03:45:45 +03:00
|
|
|
char *str = (char *)malloc(n * sizeof(char));
|
|
|
|
scanf("%s", str);
|
2018-03-19 20:39:14 +03:00
|
|
|
PrintSortedPermutations(str);
|
2020-04-24 03:45:45 +03:00
|
|
|
free(str);
|
2018-03-19 20:39:14 +03:00
|
|
|
return 0;
|
|
|
|
}
|