Untitled

 avatar
unknown
plain_text
a year ago
2.4 kB
3
Indexable
import java.util.Scanner;

public class Solution {
	static Queue queue = new Queue(10000);
	static int N, max;
	static String input;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);

		int T = sc.nextInt();
		sc.nextLine();
		for (int t = 1; t <= T; t++) {
			input = sc.next();
			N = sc.nextInt();

			queue.reset();
			max = 0;
			queue.push(input);
			for (int i = 0; i < N; i++) {
				int len = queue.length();
				for (int j = 0; j < len; j++) {
					String number = queue.pop();
					String[] S = number.split("");

					for (int n = 0; n < S.length - 1; n++) {
						for (int m = n + 1; m < S.length; m++) {
							String temp = S[m];
							S[m] = S[n];
							S[n] = temp;

							String res = "";
							for (int k = 0; k < S.length; k++) {
								res += S[k];
							}

							temp = S[n];
							S[n] = S[m];
							S[m] = temp;

							int toNum = Integer.parseInt(res);
							int qLen = queue.length();
							int front = queue.front();

							boolean exist = false;
							if (qLen != 0) {
								for (int k = front; k < front + qLen; k++) {
									int x = Integer.parseInt(queue.valueOf(k));
									if (x == toNum) {
										exist = true;
										break;
									}
								}
								if (!exist) {
									if (i == N - 1) {
										if (toNum > max)
											max = toNum;
									}
									queue.push(res);
								}

							} else {
								max = toNum;
								queue.push(res);
							}

							if (exist)
								break;

						}
					}
				}

			}
			System.out.println("Case #" + t);
			System.out.println(max);

		}

		sc.close();
	}

}

class Queue {
	private int front, rear, capacity;
	private String queue[];

	Queue(int c) {
		front = rear = 0;
		capacity = c;
		queue = new String[capacity];
	};

	void push(String data) {
		queue[rear] = data;
		rear++;
	};

	String pop() {
		String res = queue[front];
		if (rear == capacity - 1)
			rear = 0;
		if (front == capacity - 1)
			front = 0;
		front++;
		return res;
	};

	void reset() {
		front = rear = 0;
	};

	boolean empty() {
		return front == rear;
	};

	String valueOf(int index) {
		return queue[index];
	};

	int length() {
		return rear - front;
	};

	int front() {
		return front;
	};

	int rear() {
		return rear;
	};
}