using System; using System.Linq; using System.Collections.Generic; namespace Algorithm { class Program { static void Main(string[] args) { var X = Console.ReadLine().ToCharArray().OrderByDescending(z => z).ToArray(); var prev = new char[X.Length]; Array.Copy(X, prev, X.Length); var first = true; do { if (first) first = false; else { var s = new string(X); if (s[0] == '0') break; if (new string(prev) != s) { Console.WriteLine(s); return; } } } while (PrevPermutation(X)); Console.WriteLine(-1); } public static bool PrevPermutation(T[] array, int index, int length, Comparison comp) { if (length <= 1) return false; for (int i = length - 1; i > 0; i--) { int k = i - 1; if (comp(array[k], array[i]) > 0) { int j = Array.FindLastIndex(array, delegate (T x) { return comp(array[k], x) > 0; }); Swap(ref array[k], ref array[j]); Array.Reverse(array, i, length - i); return true; } } Array.Reverse(array, index, length); return false; } public static bool PrevPermutation(T[] array) where T : IComparable { return PrevPermutation(array, 0, array.Length, Comparer.Default.Compare); } public static void Swap(ref T one, ref T two) { var temp = one; one = two; two = temp; } } }