View Code of Problem 3873

#include<bits/stdc++.h>
using namespace std;

char s[12];
int n, k, len;
char ans[12], ans2[12];
bool visit[11];
char temp[11];

bool cmp(char a, char b)
{
	return a > b;
}

void rev()
{
	for (int i = 0; i < len; i++)
	{
		int minn = s[i], index = i;
		for (int j = i + 1; j < len; j++)
		{
			if (s[j] <= minn)
			{
				if (i == 0 && s[j] == '0')
					continue;
				else
				{
					minn = s[j];
					index = j;
				}
			}
		}
		if (index != i)
			swap(s[i], s[index]);
	}
}

void DFS(int depth, int index)
{
	if (depth == k || index == len)
	{
		if (strcmp(s, ans) < 0)
			strcpy(ans, s);
		if (strcmp(s, ans2) > 0)
			strcpy(ans2, s);
		return;
	}
	for (int i = index; i < len; i++)
	{
		if (index == 0 && s[i] == '0')
			continue;
		swap(s[i], s[index]);
		if (s[i] != s[index])
			DFS(depth + 1, index + 1);
		else
			DFS(depth, index + 1);
		swap(s[i], s[index]);
	}
}

int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%s%d", s, &k);
		len = strlen(s);
		if (k >= len - 1)
		{
			rev();
			printf("%s ", s);
			sort(s, s + len, cmp);
			puts(s);
			continue;
		}
		strcpy(ans, s);
		strcpy(ans2, s);
		DFS(0, 0);
		printf("%s %s\n", ans, ans2);
	}
	return 0;
}

Double click to view unformatted code.


Back to problem 3873