const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let n, m;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  if (c % 2 === 1) {
    [n, m] = d.split(' ').map(Number);
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  let sum = arr.reduce((a, x) => a + x, 0);

  console.log(Math.min(m, sum));

  c++;
});

const main = data => {
  const t = data[0];

  for (let i = 0; i < t; i++) {
    const [n, m] = data[i * 2 + 1].split(' ').map(x => +x);
    const arr = data[i * 2 + 2].split(' ').map(x => +x);

    for (let j = 1; j < n; j++) {
      while (arr[j] > 0 && arr[0] < m) {
        arr[j]--;
        arr[0]++;
      }
    }

    console.log(arr[0]);
  }
};

let data = '';

process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
  data = data.split('\n');

  main(data);
});

function processData(input) {
    //Enter your code here
    input = input.trim().split("\n")
    input.shift()
    let arr = []
    for(let i = 0; i < input.length; i++){
        var first = input[i].trim().split(" ").map(Number)
        var val = first[1]
        arr = input[i+1].trim().split(" ").map(Number)
        console.log(grade(val, arr))
        i = i + 1
    }

    function grade(val, arr){
        let sum = 0
        let len = arr.length
        for(let k = 0; k < len; k++){
            sum = sum + arr[k]
        }
        let aver = sum / len
        let top = 0
        if(val <= sum){
            top = val
        }
        else{
            top = sum
        }
        return top
    }
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

process.stdin.resume()
process.stdin.setEncoding('utf-8')

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  while(t--) {
    const [n, m] = readInts(input, ptr++)
    let ai = readInts(input, ptr++)
    let sum = ai.reduce((a, b) => a + b, 0)
    wr(Math.min(sum, m))
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = [];
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var N = one[0];
    var M = one[1];
    var list = nextIntArray();
    var sum = 0;
    for(var j = 0; j < N; j++){
      sum += list[j];
    }
    output[i] = Math.min(sum , M);
  }
  myout(myconv(output, 9));
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function solution(n, m, a) {
  let d = m - a[0];

  for(let i = 1; i < n; i++){
    d -= a[i];
    if (d <= 0){
      d = 0;
      break;
    }
  }

  return m - d;
}

function main() {
    const N = parseInt(readline());

    for(let i = 0; i < N; i++){
        const line1 = readline().split(' ').map(item => parseInt(item));
        const line2 = readline().split(' ').map(item => parseInt(item));
        console.log(solution(line1[0], line1[1], line2));
    }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function solution(n, m, a) {
  let s = 0;
  a.map(i => s+=i);
  return Math.min(m, s);
}

function main() {
    const N = parseInt(readline());

    for(let i = 0; i < N; i++){
        const line1 = readline().split(' ').map(item => parseInt(item));
        const line2 = readline().split(' ').map(item => parseInt(item));
        console.log(solution(line1[0], line1[1], line2));
    }
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let answer = "";
let n, m;

let lines = [];

rl.on('line', (t)=>{
    lines.push(t);
}).on('close', ()=>{
    let t = parseInt(lines[0]);
    for(let i = 0; i < t; i++){
        let marks = lines[i * 2 + 2].split(" ");
        [n,m] = lines[i * 2 + 1].split(' ');
        //console.log(n + " " + m);
        let my_mark = parseInt(marks[0]);
        let sum = 0;
        for(let j = 1; j < parseInt(n); j++){
            sum += parseInt(marks[j]);
        }
        if(sum + my_mark > parseInt(m))
            answer += m + '\n';
        else{
            answer += (sum + my_mark) + '\n'
        }
    }
    console.log(answer);
});

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u, 10); }); });
    var t = lines.shift()[0];
    while (t > 0) {
        var _a = lines.shift(), n = _a[0], m = _a[1];
        var scores = lines.shift();
        var myScore = scores[0];
        var i = 1;
        while (i < scores.length && myScore < m) {
            myScore += scores[i];
            i++;
        }
        if (myScore > m) {
            console.log(m);
        }
        else {
            console.log(myScore);
        }
        t--;
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

// Time Complexity O(n)
function processData(input) {
    //Enter your code here
    var data = input.trim().split('\n')
    var tcs = Number(data[0])
    var line = 1
    for(var i = 0;i<tcs;i++){
        var [n,m] = data[line].trim().split(' ').map(a=>parseInt(a))
        line++
        var arr = data[line].trim().split(' ').map(a=>parseInt(a))
        line++
        var sum = 0
        for(var j = 0;j< n;j++){
            sum += arr[j]
        }
        // console.log(sum)
        var res = Math.min(sum,m)
        console.log(res)
    }

}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
    let r = [];
    for(let i = 0 ; i < t; i++) {
       let [n, m] = nl.nums();
       let a = nl.nums();
       let s = a.reduce((x,y) => x + y, 0);
       r.push(Math.min(m, s));

    }
	console.log(r.join('\n'));

};

process.stdin.on('end', sol);

'use strict'

const problem = (n, m, a) => {
    let x = a[0];
    for(let i = 1; i < n; i++) if ((x += a[i]) >= m) return m;
    return x;
};

let t = +readline()
while(t--) {
    const nm = readline().split(' ');
    print(problem(+nm[0], +nm[1], readline().split(' ').map(i => +i)));
}

var tests= readline();

for(var n=0;n<tests;n++){
    var inputLine=readline().split(" ");
    var max=inputLine[1];
    var output=null;

    var scores=readline().split(" ").map(function(e){return parseInt(e)});

    for(var i=1;i<scores.length;i++){
        scores[0]+= scores[i];
        if(scores[0]>=max){scores[0]=max;break;}
    }//for each score

    end:print(`${scores[0]}`);

}//for each test

//var input = readline();

var T = parseInt(readline());
while (T-- > 0) {
    var kk = readline().split(" ").map(x => parseInt(x));
    var n = kk[0], m = kk[1];
    var ar = readline().split(' ').map(x => parseInt(x));
    var sum = ar.reduce((a, b) => a + b);
    print(m >= sum ? sum : m);
}

'use strict'

const problem = (n, m, a) => {
    let x = a[0];
    for(let i = 1, x = 0; i < n; i++) if ((x += a[i]) >= m) return m;
    return x;
};

let t = +readline()
while(t--) {
    const nm = readline().split(' ');
    print(problem(+nm[0], +nm[1], readline().split(' ').map(i => +i)));
}

'use strict'

const problem = (n, m, a) => {
    if (n > m) return 0;
    let r = 1;

    for (let i = 0; i < n - 1; i++)
        for (let j = i + 1; j < n; j++)
            r = (r * (a[j] -= a[i])) % m;

    return Math.abs(r);
}

const nm = readline().split(' ').map(i => +i);
const n = nm[0], m = nm[1];

print(problem(n, m, readline().split(' ').map(i => +i)))

// Time Complexity O(n)
function processData(input) {
    //Enter your code here
    var data = input.trim().split('\n')
    var tcs = Number(data[0])
    var line = 1
    for(var i = 0;i<tcs;i++){
        var [n,m] = data[line].trim().split(' ').map(a=>parseInt(a))
        line++
        var arr = data[line].trim().split(' ').map(a=>parseInt(a))
        line++
        var sum = 0
        for(var j = 0;j< n;j++){
            sum += arr[j]
        }
        console.log(sum)
        var res = Math.min(sum,m)
        console.log(res)
    }

}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});


function deathNote (restArgs) {
	const days = parseInt(restArgs[0]);
	const limit = parseInt(restArgs[1]);
	const names = readline().split(" ");
	var current = 0;
	var pages = "";
	var i;
	for (i =0; i<days;i++) {
		current += parseInt(names[i]);
		pages += Math.floor(current/limit)+" ";
		current = current % limit;
	}
	return pages.trim();
}

print(deathNote(readline().split(" ")));

function main(){
   var r = readline().split(' ');
   var n = r[0];
   var m = r[1];
   var arr = readline().split(' ');
   var result = [];
   var o = 0;
   arr.forEach((v,i)=>{
        v =+v + +o;
        result.push(parseInt(v/m));
        o = v%m;
   });
   print(result.join(' '));
}

main();

var m = parseInt(readline().split(' ')[1]);
var l = 0;

print(readline().split(' ').map(function(order){
    order = parseInt(order) + l;
    l = order % m

    return parseInt(order / m);
}).join(' '));

var line = readline().split(" ")
var names = readline().split(" ")
var limitPage = line[1]
var remaining = 0;
var responseArray = []
for(var i = 0; i < names.length; i++){
    var numOfNames = parseInt(names[i]) + remaining
    responseArray.push(Math.floor(numOfNames / limitPage))
    remaining = numOfNames % limitPage
}

print(responseArray.join(" "))

var nm = readline().split(' ').map(Number);
var n = nm[0];
var m = nm[1];

var a = readline().split(' ').map(Number);
var output = ''
var ostatok = 0;

for (var i=0; i<n; i++){
	if (ostatok == 0) output += Math.floor(a[i]/m) + ' ';
	else output += (Math.floor((a[i] - ostatok)/m) + 1) + ' ';
	if (a[i] <= ostatok) ostatok = ostatok - a[i];
	else ostatok = m - ((a[i] - ostatok) % m);
}

print (output);

// const print = require('lol-io').print;
// const readline = require('lol-io').readline;

var nm = readline().split(' ').map(n => parseInt(n));
var n = nm[0];
var m = nm[1];
var numNames = readline().split(' ').map(n => parseInt(n));

var prev = 0;
var res = [];
for (var i = 0; i < numNames.length; i++) {
  var numName = numNames[i];
  var total = prev + numName;
  var pages = parseInt(total/m);
  prev = total % m;
  res.push(pages);
}
print(res.join(' '));

// const print = require('lol-io').print;
// const readline = require('lol-io').readline;
//

var nm = readline().split(' ').map(n => parseInt(n));
var n = nm[0];
var m = nm[1];
var numNames = readline().split(' ').map(n => parseInt(n));

var prev = 0;
var res = [];
for (var i = 0; i < numNames.length; i++) {
  var numName = numNames[i];
  var total = prev + numName;
  var pages = parseInt(total/m);
  prev = total % m;
  res.push(pages);
}
print(res.join(' '));

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray(Number);
  const books = is.nextArray(Number);
  let container = 0, turnPage;
  for (let i = 0; i < n; i += 1) {
    turnPage = 0;
    container += books[i];
    turnPage = Math.trunc(container / m);
    container %= m;
    process.stdout.write(String(turnPage) + ' ');
  }
  console.log();
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

const readline = require('readline')

var interface = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
})

var n, m
var nums
var lineCount = 0
interface.on('line', function (line) {
  var splits = line.trim().split(' ').map(x => parseInt(x))
  if (lineCount == 0) {
    n = splits[0]
    m = splits[1]
    lineCount ++
  } else if (lineCount == 1) {
    nums = line.trim().split(' ')
    var rest = 0
    var answer = ''
    for (var i = 0; i < nums.length; i++) {
      var pages

      if (nums[i] < rest) {
        // console.log('nums[i]:' + nums[i], 'rest:' + rest, 'result:0')
        pages = 0
        rest = rest - nums[i]
      } else {
        pages = Math.floor((nums[i] - rest) / m)
        if (rest > 0) {
          pages += 1
        }
        // console.log('nums[i]:' + nums[i], 'rest:' + rest, 'result:' + pages)
        if ((nums[i] - rest) % m == 0) {
          rest = 0
        } else {
          rest = m - ((nums[i] - rest) % m)
        }
      }
      answer += pages + ' '
    }
    console.log(answer)
    process.exit()
  }
})

const readline = require('readline')

var interface = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
})

var n, m
var nums
var lineCount = 0
interface.on('line', function (line) {
  var splits = line.trim().split(' ').map(x => parseInt(x))
  if (lineCount == 0) {
    n = splits[0]
    m = splits[1]
    lineCount ++
  } else if (lineCount == 1) {
    nums = line.trim().split(' ')
    var rest = 0
    var answer = ''
    for (var i = 0; i < nums.length; i++) {
      var pages

      if (nums[i] < rest) {
        pages = 0
        rest = rest - nums[i]
      } else {
        pages = Math.floor((nums[i] - rest) / m)
        if (rest > 0) {
          pages += 1
        }
        if ((nums[i] - rest) % m == 0) {
          rest = 0
        } else {
          rest = m - ((nums[i] - rest) % m)
        }
      }
      // console.log(pages + ' ')
      answer += pages + ' '
    }
    console.log(answer)
    process.exit()
  }
})

var nm = readline().split(' ').map(Number);
var n = nm[0];
var m = nm[1];

var a = readline().split(' ').map(Number);
var output = ''
var ostatok = 0;

for (var i=0; i<n; i++){
	if (ostatok == 0) output += Math.floor(a[i]/m) + ' ';
	else output += (Math.floor((a[i] - ostatok)/m) + 1) + ' ';
	ostatok = m - ((a[i] - ostatok) % m);
}

print (output);

var nm = readline().split(' ').map(Number);
var n = nm[0];
var m = nm[1];

var a = readline().split(' ').map(Number);
var output = ''
var ostatok = 0;

for (var i=0; i<n; i++){
	if (ostatok == 0) output += Math.floor(a[i]/m) + ' ';
	else output += (Math.floor((a[i] - ostatok)/m) + 1) + ' ';
	ostatok = (m - a[i] + ostatok) % m;
}

print (output);


var n = +readline(),
    l = readline().split(" ").map(item => +item).sort((a, b) => a - b),
    ans = new Array(n);

ans[0] = l[0];
ans[n - 1] = l[1];

for(var i = 2, pos = 1; i < n - 1; i+= 2, pos++) {
    ans[pos] = l[i];
    ans[n - pos - 1] = l[i + 1];
}

if (n % 2) {
    ans[pos] = l[i];
}

print(ans.join(" "));

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0];
var s = readline().split(" ").map(function(x) { return parseInt(x); });
s.sort(function(a,b) {return a-b;});
var s_init = s.slice();
var ans2 = Array(n).fill(0);
var i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans2[i] = s[k];
		i--;
	}
	else {
		ans2[j] = s[k];
		j++;
	}
	cc++;
}
for (var i=0; i<n; i++) s[i] = ans2[i];
var ans = 0;
for (var i=0; i<n; i++) ans = Math.max(ans, Math.abs(s[i]-s[(i+1)%n]));

s.sort(function(a,b) {return b-a;});
ans3 = Array(n).fill(0);
i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans3[i] = s[k];
		i--;
	}
	else {
		ans3[j] = s[k];
		j++;
	}
	cc++;
}
var ans_new = 0;
for (var i=0; i<n; i++) ans_new = Math.max(ans_new, Math.abs(ans3[i]-ans3[(i+1)%n]));
if (ans_new < ans) {
	ans = ans_new;
	s = ans3.slice();
}
else {
	s = ans2.slice();
}

for (var iter=0; iter<35; iter++) {
	for (var i=0; i<n; i++)
		for (var j=i+1; j<n; j++) {
			var t = s[i];
			s[i] = s[j];
			s[j] = t;
			var new_ans = 0;
			for (var k=0; k<n; k++) new_ans = Math.max(new_ans, Math.abs(s[k]-s[(k+1)%n]));
			if (new_ans <= ans) {
				ans = new_ans;
				continue;
			}
			t = s[i];
			s[i] = s[j];
			s[j] = t;
		}
}
var down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort(function(a,b) {return a-b;});
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
	w.sort(function(a,b) {return a-b;});
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans = Math.max(new_ans, Math.abs(res[k]-res[(k+1)%n]));
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}
down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort(function(a,b) {return a-b;});
	var nnew = Array(n).fill(0);
	var res = Array(n).fill(0);
	res[0] = w[n-1];
	nnew[n-1] = 1;
	var aa = 1, bb = n-1;
	for (var j=0; j<n-1; j++) {
		var x = 0;
		if (j % 2 === 0) x = res[aa-1];
		else x = res[(bb+1)%n];

		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		x = w[ind];

		if (j%2===0) {
			res[aa] = x;
			aa++;
		}
		else {
			res[bb] = x;
			bb--;
		}
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
    w.sort(function(a,b) {return a-b;});
	var nnew = Array(n).fill(0);
	var res = Array(n).fill(0);
	res[0] = w[n-1];
	nnew[n-1] = 1;
	var aa = 1, bb = n-1;
	for (var j=0; j<n-1; j++) {
		var x = 0;
		if (j % 2 === 0) x = res[aa-1];
		else x = res[(bb+1)%n];

		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		x = w[ind];

		if (j%2===0) {
			res[aa] = x;
			aa++;
		}
		else {
			res[bb] = x;
			bb--;
		}
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans = Math.max(new_ans, Math.abs(res[k]-res[(k+1)%n]));
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}
write(s.join(" "));

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0];
var s = readline().split(" ").map(function(x) { return parseInt(x); });
s.sort((a,b)=>a>b);
var ans2 = Array(n).fill(0);
var i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans2[i] = s[k];
		i--;
	}
	else {
		ans2[j] = s[k];
		j++;
	}
	cc++;
}
for (var i=0; i<n; i++) s[i] = ans2[i];
var ans = 0;
for (var i=0; i<n; i++) ans += Math.abs(s[i]-s[(i+1)%n]);
for (var iter=0; iter<20; iter++) {
	for (var i=0; i<n; i++)
		for (var j=i+1; j<n; j++) {
			var t = s[i];
			s[i] = s[j];
			s[j] = t;
			var new_ans = 0;
			for (var k=0; k<n; k++) new_ans += Math.abs(s[k]-s[(k+1)%n]);
			if (new_ans < ans) {
				ans = new_ans;
				continue;
			}
			t = s[i];
			s[i] = s[j];
			s[j] = t;
		}
}
write(s.join(" "));
//for (var i=0; i<n; i++) write(ans[i]," ");

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0];
var s = readline().split(" ").map(function(x) { return parseInt(x); });
s.sort((a,b)=>a>b);
var s_init = s.slice();
var ans2 = Array(n).fill(0);
var i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans2[i] = s[k];
		i--;
	}
	else {
		ans2[j] = s[k];
		j++;
	}
	cc++;
}
for (var i=0; i<n; i++) s[i] = ans2[i];
var ans = 0;
for (var i=0; i<n; i++) ans += Math.abs(s[i]-s[(i+1)%n]);
for (var iter=0; iter<35; iter++) {
	for (var i=0; i<n; i++)
		for (var j=i+1; j<n; j++) {
			var t = s[i];
			s[i] = s[j];
			s[j] = t;
			var new_ans = 0;
			for (var k=0; k<n; k++) new_ans += Math.abs(s[k]-s[(k+1)%n]);
			if (new_ans < ans) {
				ans = new_ans;
				continue;
			}
			t = s[i];
			s[i] = s[j];
			s[j] = t;
		}
}
var down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans += Math.abs(res[k]-res[(k+1)%n]);
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}
down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = Array(n).fill(0);
	res[0] = w[n-1];
	nnew[n-1] = 1;
	var aa = 1, bb = n-1;
	for (var j=0; j<n-1; j++) {
		var x = 0;
		if (j % 2 === 0) x = res[aa-1];
		else x = res[(bb+1)%n];

		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		x = w[ind];

		if (j%2===0) {
			res[aa] = x;
			aa++;
		}
		else {
			res[bb] = x;
			bb--;
		}
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = Array(n).fill(0);
	res[0] = w[n-1];
	nnew[n-1] = 1;
	var aa = 1, bb = n-1;
	for (var j=0; j<n-1; j++) {
		var x = 0;
		if (j % 2 === 0) x = res[aa-1];
		else x = res[(bb+1)%n];

		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		x = w[ind];

		if (j%2===0) {
			res[aa] = x;
			aa++;
		}
		else {
			res[bb] = x;
			bb--;
		}
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
//write(" Mindiff = ", down);
//write("\n So ans = ",res.join(" "));
//write("\n");
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans += Math.abs(res[k]-res[(k+1)%n]);
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}
write(s.join(" "));

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0];
var s = readline().split(" ").map(function(x) { return parseInt(x); });
s.sort((a,b)=>a>b);
var s_init = s.slice();
var ans2 = Array(n).fill(0);
var i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans2[i] = s[k];
		i--;
	}
	else {
		ans2[j] = s[k];
		j++;
	}
	cc++;
}
for (var i=0; i<n; i++) s[i] = ans2[i];
var ans = 0;
for (var i=0; i<n; i++) ans += Math.abs(s[i]-s[(i+1)%n]);
for (var iter=0; iter<20; iter++) {
	for (var i=0; i<n; i++)
		for (var j=i+1; j<n; j++) {
			var t = s[i];
			s[i] = s[j];
			s[j] = t;
			var new_ans = 0;
			for (var k=0; k<n; k++) new_ans += Math.abs(s[k]-s[(k+1)%n]);
			if (new_ans < ans) {
				ans = new_ans;
				continue;
			}
			t = s[i];
			s[i] = s[j];
			s[j] = t;
		}
}
var down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
//write(" Mindiff = ", down);
//write("\n So ans = ",res.join(" "));
//write("\n");
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans += Math.abs(res[k]-res[(k+1)%n]);
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}

write(s.join(" "));

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0];
var s = readline().split(" ").map(function(x) { return parseInt(x); });
s.sort((a,b)=>a>b);
var ans = Array(n).fill(0);
var i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans[i] = s[k];
		i--;
	}
	else {
		ans[j] = s[k];
		j++;
	}
	cc++;
}
write(ans.join(" "));
//for (var i=0; i<n; i++) write(ans[i]," ");

var nums = readline().split(" ").map(function(x) { return parseInt(x); });
var n = nums[0];
var s = readline().split(" ").map(function(x) { return parseInt(x); });
s.sort((a,b)=>a>b);
var s_init = s.slice();
var ans2 = Array(n).fill(0);
var i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans2[i] = s[k];
		i--;
	}
	else {
		ans2[j] = s[k];
		j++;
	}
	cc++;
}
for (var i=0; i<n; i++) s[i] = ans2[i];
var ans = 0;
for (var i=0; i<n; i++) ans = Math.max(ans, Math.abs(s[i]-s[(i+1)%n]));

s.sort((a,b)=>a<b);
ans3 = Array(n).fill(0);
i = n-1, j = 0, cc = 0;
for (var k=n-1; k>=0; k--) {
	if (cc%2===0) {
		ans3[i] = s[k];
		i--;
	}
	else {
		ans3[j] = s[k];
		j++;
	}
	cc++;
}
var ans_new = 0;
for (var i=0; i<n; i++) ans_new = Math.max(ans_new, Math.abs(ans3[i]-ans3[(i+1)%n]));
if (ans_new < ans) {
	ans = ans_new;
	s = ans3.slice();
}
else {
	s = ans2.slice();
}

for (var iter=0; iter<35; iter++) {
	for (var i=0; i<n; i++)
		for (var j=i+1; j<n; j++) {
			var t = s[i];
			s[i] = s[j];
			s[j] = t;
			var new_ans = 0;
			for (var k=0; k<n; k++) new_ans = Math.max(new_ans, Math.abs(s[k]-s[(k+1)%n]));
			if (new_ans < ans) {
				ans = new_ans;
				continue;
			}
			t = s[i];
			s[i] = s[j];
			s[j] = t;
		}
}
var down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = [];
	res.push(w[n-1]);
	nnew[n-1] = 1;
	var x = w[n-1];
	for (var j=0; j<n-1; j++) {
		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		res.push(w[ind]);
		x = w[ind];
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans = Math.max(new_ans, Math.abs(res[k]-res[(k+1)%n]));
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}
down = 0, up = 1000000000+10000;
while (up > down) {
	var mid = Math.floor((up + down)/2);
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = Array(n).fill(0);
	res[0] = w[n-1];
	nnew[n-1] = 1;
	var aa = 1, bb = n-1;
	for (var j=0; j<n-1; j++) {
		var x = 0;
		if (j % 2 === 0) x = res[aa-1];
		else x = res[(bb+1)%n];

		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		x = w[ind];

		if (j%2===0) {
			res[aa] = x;
			aa++;
		}
		else {
			res[bb] = x;
			bb--;
		}
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok === 1) up = mid;
	else down = mid + 1;
}
if (down >= 0) {
	var mid = down;
	var Ok = 1;
	var w = s_init.slice();
	w.sort((a,b)=>a>b);
	var nnew = Array(n).fill(0);
	var res = Array(n).fill(0);
	res[0] = w[n-1];
	nnew[n-1] = 1;
	var aa = 1, bb = n-1;
	for (var j=0; j<n-1; j++) {
		var x = 0;
		if (j % 2 === 0) x = res[aa-1];
		else x = res[(bb+1)%n];

		var mx_diff = -100000000000;
		var ind = -1;
		for (var k=0; k<n; k++)
			if (nnew[k] === 0) {
				var diff = Math.abs(w[k] - x);
				if (diff > mx_diff && diff <= mid) {
					mx_diff = diff;
					ind = k;
				}
			}
		if (ind < 0) {
			Ok = 0;
			break;
		}
		nnew[ind] = 1;
		x = w[ind];

		if (j%2===0) {
			res[aa] = x;
			aa++;
		}
		else {
			res[bb] = x;
			bb--;
		}
	}
	if (Ok)
		if (Math.abs(res[0] - res[n-1]) > mid) {
			var t = res[n-1];
			res[n-1] = res[n-2];
			res[n-2] = t;
			for (var k=0; k<n; k++)
				if (Math.abs(res[k]-res[(k+1)%n]) > mid) {Ok = 0; break;}
		}
	if (Ok) {
		var new_ans = 0;
		for (var k=0; k<n; k++) new_ans = Math.max(new_ans, Math.abs(res[k]-res[(k+1)%n]));
		if (new_ans < ans) {
			ans = new_ans;
			s = res.slice();
		}
	}
}
write(s.join(" "));

var intmax = 10000000000;
    n = +readline(),
    l = readline().split(" ").map(item => +item).sort((a, b) => a - b),
    ans = new Array(n);

ans[0] = l[0];
ans[n - 1] = l[1];

for(var i = 2, pos = 1; i <= Math.floor(n/2); i += 2, pos++) {
    ans[pos] = l[i];
    ans[n - pos - 1] = l[i + 1];
}

if (n % 2) {
    ans[pos] = l[i];
}

print(ans.join(" "));

var n = +readline(),
    l = readline().split(" ").map(item => +item).sort((a, b) => a - b),
    ans = [];

for (var i = 0; i < n; i++) {
    ans.push(0);
}

ans[0] = l[0];
ans[n - 1] = l[1];

for(var i = 2, pos = 1; i <= Math.floor(n/2); i += 2, pos++) {
    ans[pos] = l[i];
    ans[n - pos - 1] = l[i + 1];
}

if (n % 2) {
    ans[pos] = l[i];
}

print(ans.join(" "));


var m1 = {}, m2 = {};
var n, m;
var token = [];
var ans = "";

token = readline().split(' ');
n = parseInt(token[0]);
m = parseInt(token[1]);

for(var i=0;i<m;i++) {
  token = readline().split(' ');
  m1[token[0]]=token[1];
  m2[token[1]]=token[0];
}

token = readline().split(' ');

for(var i=0;i<n;i++) {
  var w1="", w2="";

  if(m1[token[i]]==null) {
    w2=token[i];
    w1=m2[w2];
  }
  else {
    w1=token[i];
    w2=m1[w1];
  }

  if(i>0) ans+=" ";

  if(w1.length<=w2.length) {
    ans+=w1;
  }
  else {
    ans+=w2;
  }
}

print(ans);

const input = [];

const RL = require('readline').createInterface({
   input : process.stdin,
   output : process.stdout
});

RL.on('line', line => input.push(line));

RL.on('close', () => {
  const [n, m] = input[0].split(' ').map(x => parseInt(x));
  const map = {};

  for (let i = 0; i < m; i += 1) {
    let [w1, w2] = input[i+1].split(' ');

    map[w1] = {len: w1.length, w: w2};
    map[w2] = {len: w2.length, w: w1};
  }

  const answer = [];
  const dict = input[m+1].split(' ');

  for (const w of dict) {
    if (map[w].len <= map[w].w.length) {
      answer.push(w);
    } else {
      answer.push(map[w].w);
    }
    answer.push(' ');
  }

  console.log(answer.join(''));
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

function readLine() {
	return inputString[currentLine++];
}

const store = {};

function main() {
	let [n, m] = readLine()
		.split(' ')
		.map(x => x >> 0);
	let dic = {};

	while (m--) {
		let [key, value] = readLine().split(' ');
		dic[key] = value;
	}

	let lec = readLine().split(' ');
	const res = lec.map(word =>
		word.length <= dic[word].length ? word : dic[word]
	);

	console.log(res.join(' '));
}

var input = readline().split(" ").map(Number), n = input[0], m = input[1];
var lang1to2 = {}, lang2to1 = {};

for(var i = 0; i < m; i++){
	input = readline().split(" ");

	lang1to2[input[0]] = input[1];
	lang2to1[input[1]] = input[0];
}

var speech = readline().split(" ");

for(var i = 0; i < n; i++){
	if(lang1to2[speech[i]] != undefined){
		if(speech[i].length <= lang1to2[speech[i]].length){
			write(speech[i]);
		}
		else{
			write(lang1to2[speech[i]]);
		}
	}
	else{
		if(speech[i].length <= lang2to1[speech[i]].length){
			write(speech[i]);
		}
		else{
			write(lang2to1[speech[i]]);
		}
	}

	write(" ");
}

function main(n,m,arr,prof) {

    var ans = ""

    for(var i = 0 ; i < n ; i++){
      for(var j = 0 ; j  < m ; j++){
        if(prof[i] === arr[j][0]){
          if(prof[i].length > arr[j][1].length)ans = ans + arr[j][1] + " ";
          else ans = ans + arr[j][0] + " ";
          break;
        }
      }
    }

    print(ans);

}

//
// main(4,3,[["codeforces","codesecrof"],["contest","round"],["letter","message"]],
// ["codeforces","contest","letter","contest"])
//

var nm = readline().split(" ");

var arr = []

for(var i = 0 ; i < parseInt(nm[1]) ; i++){
  arr[i] = readline().split(" ");
}

var prof = readline().split(" ");

main(parseInt(nm[0]),parseInt(nm[1]),arr,prof);

var t = readline().split(' ');
var n = t[0];
var m = t[1];
var i = 0, inpStr1, slo1 = [], slo2 = [];

for(i=0; i<m; i++)
{
  inpStr1 = readline().split(' ');

  slo1[i] = inpStr1[0];
  slo2[i] = inpStr1[1];
}

var inpStr2 = readline().split(' '), outStr = "";

for(i=0; i<n; i++)
{
  for(var k=0; k<m; k++)
  {
    if (inpStr2[i] == slo1[k] && slo1[k].length > slo2[k].length)
    {
      outStr = outStr + slo2[k];
    }
    else if (inpStr2[i] == slo1[k])
    {
      outStr = outStr + slo1[k];
    }
  }
  if (i<n) outStr = outStr + " ";
}

print(outStr);

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    translate = {};
  for (var i = 0; i < m; ++i) {
    var tokens = tokenize(readline());
    translate[tokens[0]] = tokens[1];
  }
  var speech = tokenize(readline()),
      result = [];
  for (var i = 0; i < n; ++i) {
    var a = speech[i], b = translate[a];
    if (a.length <= b.length) {
      result.push(a);
    } else {
      result.push(b);
    }
  }
  print(result.join(' '));
}

main();

/* TEST CASE
input
4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest
output
codeforces round letter round
input
5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll
output
hbnyiyc joll joll un joll

*/

function main() {
	var splitted = readline().split(' ');
	var nWordsLectured = parseInt(splitted[0]);
	var nWordsInDictionary = parseInt(splitted[1]);
	var i;
	var wordMap = {};
	for (i = 0; i < nWordsInDictionary; i++) {
		splitted = readline().split(' ');
		if(splitted[0].length <= splitted[1].length) {
			wordMap[splitted[1]] = splitted[0];
		} else {
			wordMap[splitted[0]] = splitted[1];
		}
	}

	splitted = readline().split(' ');

	for (i = 0; i < nWordsLectured; i++) {
		var newShorter = wordMap[splitted[i]];
		if (newShorter != null) {
			splitted[i] = newShorter;
		}
	}
	print(splitted.join(' '));
}

main();

var line1 = readline().split(' ')
var n = line1[0];
var m = line1[1];
var words = {};

for (var i=0; i<m; i++) {
  var line = readline().split(' ')
  var key = line[0];
  var val = line[1];
  words[key] = val;
}

var lastline = readline().split(' ')
var answer = [];
for (var i=0; i<n; i++) {
  var word = lastline[i];
  var word2 = words[word];

  if (word.length <= word2.length) {
    answer[i] = word;
  } else {
    answer[i] = word2;
  }
}

print(answer.join(' '));

(function() {
    function createDictionary(count) {
        var result = [];
        for (var i = 0; i < count; ++i) {
            input = readline().split(' ');
            var a = input[0];
            var b = input[1];
            if (b.length >= a.length)
                b = a;
            result[a] = b;
        }
        return result;
    };

    function writeAnswer(answer) {
        for (i = 0; i < answer.count; ++i) {
            write(answer.get(answer, i));
            if (i < answer.count - 1)
                write(' ');
        }
    }

    var input = readline().split(' ');
    var n = parseInt(input[0]);
    var m = parseInt(input[1]);
    var inf = createDictionary(m);

    input = readline().split(' ');
    writeAnswer({
        count: n,
        data: input,
        dict: inf,
        get: function(self, index) {
            return self.dict[self.data[index]];
        }
    });
})()

//var input = "4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function main(){
    var mapF = {};
    var mapS = {};
    var t = readline().split(' ');
    var n = parseInt(t[0]);
    var m = parseInt(t[1]);
    for(var i = 0; i < m; i++){
        var arr = readline().split(' ');
        mapF[arr[0]] = arr[1];
        mapS[arr[1]] = arr[0];
    }
    var text = readline().split(' ');
    var ans = "";
    for(var i = 0; i < text.length; i++){
        if(text[i] in mapF){
            var val = mapF[text[i]];
            if(val.length < text[i].length)
                ans += val;
            else
                ans += text[i];
        }else{
            var val = mapS[text[i]];
            if(val.length <= text[i].length)
                ans += val;
            else
                ans += text[i];
        }
        ans += " ";
    }
    print(ans);
}
main();

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let n, m, strs, di1 ={}, di2 = {}, c = 0,
lec, arr1 = [], arr = [];
rl.on('line', input => {
    if (n && m && c < m ) {
        arr.push(input);
        let str = arr[c].split(' ')
        di1[str[0]] = str[1]
        c++;
    } else if ( c >= m ) {
        lec = input.split(' ');
        c++;
        for (let j = 0; j < lec.length; j++) {
            if (lec[j].length > di1[lec[j]].length) {
                lec[j] = di1[lec[j]]
            }
        }
        console.log(lec.join(' '))
        rl.close()
    } else {
        [n, m] = input.split(' ').map(x => +x);
    }
})

"use strict";

const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

let [lectureLength, languageWords] = [null];
let wordsA = [], wordsB = [], speech = [];

readline.on('line', line => {
    if (!lectureLength) {
        [lectureLength, languageWords] = line.split(' ');
    } else if (wordsA.length < languageWords) {
        let [a, b] = line.split(' ');
        wordsA.push(a);
        wordsB.push(b);
    } else {
        speech = line.split(' ');
        readline.close();
    }
});

readline.on('close', () => {
    writeNote();
});

const writeNote = () => {
    let result = '';
    speech.map(word => {
        let comparator = wordsB[wordsA.indexOf(word)];
        let shorter = comparator.length < word.length ? comparator : word;
        result += shorter + ' ';
    })
    console.log(result.trim());
};

var t = readline().split(' ');
var n = t[0];
var m = t[1];
var i = 0, inpStr1, slo1 = [], slo2 = [];

for(i=0; i<m; i++)
{
  inpStr1 = readline().split(' ');

  slo1[i] = inpStr1[0];
  slo2[i] = inpStr1[1];
}

var inpStr2 = readline().split(' '), outStr = "";

for(i=0; i<n; i++)
{
  for(var k=0; k<m; k++)
  {
    if (inpStr2[i] == slo1[k] && slo1[k].length > slo2[k].length)
    {
      outStr = outStr + slo2[k];
    }
    else
    {
      outStr = outStr + slo1[k];
    }
  }
  if (i>0 && i<n) outStr = outStr + " ";
}

print(outStr);

var line1 = readline().split(' ')
var n = line1[0];
var m = line1[1];
var words = {};

for (var i=0; i<m; i++) {
  var line = readline().split(' ')
  var key = line[0];
  var val = line[1];
  words[key] = val;
}

var lastline = readline().split(' ')
var answer = "";
for (var i=0; i<n; i++) {
  var word = lastline[i];
  var word2 = words[word];

  if (word.length <= word2.length) {
    answer += word;
  } else {
    answer += word2;
  }
}

print(answer);

var line0 = readline().split(' ')
print(line0)

//var input = "4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function main(){
    var mapF = {};
    var mapS = {};
    var t = readline().split(' ');
    var n = parseInt(t[0]);
    var m = parseInt(t[1]);
    for(var i = 0; i < m; i++){
        var arr = readline().split(' ');
        mapF[arr[0]] = arr[1];
        mapS[arr[1]] = arr[0];
    }
    var text = readline().split(' ');
    var ans = "";
    for(var i = 0; i < text.length; i++){
        if(text[i] in mapF){
            var val = mapF[text[i]];
            if(val.length <= text[i].length)
                ans += val;
            else
                ans += text[i];
        }else{
            var val = mapS[text[i]];
            if(val.length < text[i].length)
                ans += val;
            else
                ans += text[i];
        }
        ans += " ";
    }
    print(ans);
}
main();

const input = [];

const RL = require('readline').createInterface({
   input : process.stdin,
   output : process.stdout
});

RL.on('line', line => input.push(line));

RL.on('close', () => {
  const [n, m] = input[0].split(' ').map(x => parseInt(x));
  const map = {};

  for (let i = 0; i < m; i += 1) {
    let [w1, w2] = input[i+1].split(' ');

    map[w1] = {len: w1.length, w: w2};
    map[w2] = {len: w2.length, w: w1};
  }

  const answer = [];
  const dict = input[m+1].split(' ');

  for (const w of dict) {
    if (map[w].len < map[w].w.length) {
      answer.push(w);
    } else {
      answer.push(map[w].w);
    }
    answer.push(' ');
  }

  console.log(answer.join(''));
});


var tc = parseInt(readline());
while (tc--) {
    var n = parseInt(readline());
    var ar = readline().split(' ').map(x => parseInt(x));
    var sum = ar.reduce((a, b) => a + b);
    var MX = Math.max(...ar);
    var ok = 0;
    if (MX > sum / 2) ok = 1;
    if (sum & 1) ok = 1;
    print(ok ? 'T' : 'HL');
}

for (var t = parseInt(readline()); t > 0; t --) {
	var n = parseInt(readline());
	var arr = readline().split(' ').map(x => parseInt(x));
	var total = 0;
	var largest = 0;
	for (var i = 0; i < n; i ++) {
		total += arr[i];
		if (arr[i] > largest) largest = arr[i];
	}
	var winner = '';
	if (n === 1) {
		winner = 'T';
	} else if (largest > total - largest) {
		winner = 'T';
	} else if (total % 2 === 0) {
		winner = 'HL';
	} else {
		winner = 'T';
	}
	print(winner);
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $(), a = $(n).sort(desc)
    if (n == 1) {
      log('T')
    } else {
      if (a[0] > a.sum() - a[0]) log('T')
      else log((a.sum() - a[0] - a[0]) % 2 ? 'T' : 'HL')
    }
  }
}

// Lang: Node.js
'use strict';
let x = '', y = 0;
let print = x => console.log(x);

process.stdin.on('data', inputStdin => x += inputStdin);
process.stdin.on('end', () => { x = x.split('\n'); main(); });
let readline = () => x[y++];

// ************************ Code Start ***************************

function main() {

  var tc = parseInt(readline());
  while (tc--) {
    var n = parseInt(readline());
    var ar = readline().split(" ").map((x) => parseInt(x));
    var sum = ar.reduce((a, b) => a + b);
    var MX = Math.max(...ar);
    var ok = 0;
    if (MX > sum / 2) ok = 1;
    if (sum & 1) ok = 1;
    print(ok ? "T" : "HL");
  }
}

for (var t = parseInt(readline()); t > 0; t --) {
	var n = parseInt(readline());
	var arr = readline().split(' ').map(x => parseInt(x));
	var total = 0;
	for (var i = 0; i < n; i ++) total += arr[i];
	if (n === 1) {
		print('T');
	} else if (total % 2 === 0) {
		print('HL');
	} else {
		print('T');
	}
}

for (var t = parseInt(readline()); t > 0; t --) {
	var n = parseInt(readline());
	var arr = readline().split(' ').map(x => parseInt(x));
	var total = 0;
	var oneCount = 0;
	for (var i = 0; i < n; i ++) {
		total += arr[i];
		if (arr[i] === 1) oneCount ++;
	}
	var winner = '';
	if (n === 1) {
		winner = 'T';
	} else if (total % 2 === 0) {
		winner = 'HL';
	} else {
		winner = 'T';
	}
	if (oneCount % 2 === 0 && oneCount !== 0) {
		if (winner === 'T') {
			winner = 'HL';
		} else {
			winner = 'T';
		}
	}
	print(winner);
}

var inp = readline().split(' ');
var m = parseInt(inp[0]);
var s = parseInt(inp[1]);

var largestArr = [], smallestArr = [];
for (var i = 0; i < m; i ++) {
	largestArr.push(0);
	smallestArr.push(1);
}

var largestOn = 0, smallestOn = m - 1;
for (var i = 0; i < s; i ++) {
	if (largestOn < m) {
		largestArr[largestOn] ++;
		if (largestArr[largestOn] === 9) largestOn ++;
	} else largestArr = [-1];

	if (smallestOn >= 0 && m <= s) {
		if (i >= m) {
			smallestArr[smallestOn] ++;
			if (smallestArr[smallestOn] === 9) smallestOn --;
		}
	} else smallestArr = [-1];
}

print(s === 0 ? '-1 -1' : smallestArr.join('') + ' ' + largestArr.join(''));

for (var t = parseInt(readline()); t > 0; t --) {
	var n = parseInt(readline());
	var arr = readline().split(' ').map(x => parseInt(x));
	var odds = 0;
	var evens = 0;
	for (var i = 0; i < n; i ++) {
		if (arr[i] % 2 === 0) {
			evens ++;
		} else {
			odds ++;
		}
	}
	if (evens <= odds) {
		print('HL');
	} else {
		print('T');
	}
}


var t = readline();
var s = '';

for(var i=0; i<t; i++){

	var s = readline();

	var letter = '';
	var output = -1;

	for (var j=1; j<s.length; j++){
		if (s.charAt(j) != s.charAt(0)) {
			letter = s.charAt(j);
			s = s.replace(letter, '');
			s = s.concat(letter);
			output = s;
			break;
		} else output = -1;
	}
	print(output);
}

//var input = readline()
var k = readline()

for(var i=0; i<k; i++){
    var n = readline()

    var m = n.split('').sort().join('')
    // //print('sort: '+ m)

    // var L = Math.ceil(n.length/2)-1
    // var middle = n[L]
    // var first = n[0]
    // //print(first +' '+ middle)

    // arr.splice(0,1,middle)
    // arr.splice(L,1,first)
    // var change = arr.join('')
    // //print(change)

    // var a = n.split("").reverse().join("")
    // var c = /^(.)\1+$/.test(n) // check input same letter
    // //print(c)

     if(m[0] == m.slice(-1)) print(-1)
    // else if(n == a) print(change)
     else print (m)

}

'use strict'

var a = parseInt(readline());
var i=0;
var arr=[];

for(i;i<a;i++){
    arr[i]=readline();
}

function hwbh(a){
    var p=0;
    var i=0;
    var n='';
    for(i in a){
        if(a[i]!==a[0]){
            p=i;
            break;
        }
    }
    if(p==0){
        print('-1');
    }else{
        n=a[0];
        a[0]=a[p];
        a[p]=n;
        print(a.join(''));
    }

}
var j;
var p;
for(i in arr){
    p=0;
    for(j=0;j<=(arr[i].length-1)/2;j++){
        if(arr[i].length==1){
            print('-1');
            p=-1;
            break;
        }else if(arr[i][j]!==arr[i][arr[i].length-j-1]){
            p=1;
        }

    }
    if(p==1){
        print(arr[i]);
    }else if(p==0)
        hwbh(arr[i].split(''));
}

var t = function () {
    var input = readline();
    return parseInt(input);
} ();

for(var i=0; i<t; i++) {
    var line = readline();

    var good = "";

    var possible = false;
    for(var j=1; j<line.length; j++) {
        if( line[0] != line[j] ) {
            possible = true;
            other = j;
            break;
        }
    }
    if( possible === false ) {
        print(-1);
    } else {
        print( line[0] + line.substr(1, j-1) + line.substr(j+1) + line[j] )
    }

}

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
let t = 0
rl.on('line', (input) => {
    if (l === t + 1) {
        return 0
    }
    if (l === 0) {
        t = parseInt(input)
    } else {
        let s = input.split('')
        s.sort()
        if (s[0] !== s[s.length - 1]) {
            console.log(s.join(""))
        } else {
            console.log(-1)
        }
    }
    l++
});

var t = function () {
    var input = readline();
    return parseInt(input);
} ();

for(var i=0; i<t; i++) {
    var line = readline();

    line = line.split("").sort().toString().replace(/,/g, '');

    if(line[0]===line[line.length-1]) {
        print(-1);
    } else {
        print(line);
    }
}

var t = parseInt(readline())
var result = []

for(var i = 0; i < t; i++)
{
    var str = readline();
    var s = []
    var len = str.length;

    for(var j = 0; j < len; j++)
    {
        s.push(str[j]);
    }

    var same = 1;
    var good = 1;

    for(j = 0; j < len; j++)
    {
        if(s[j] != s[0])
        {
            same = 0;
            index = j;
            break;
        }
    }
    if(same == 1)
    {
        result.push("-1");
    }
    else
    {
        for(var j = 0; j < len; j++)
        {
            if(s[j] != s[len - 1 - j])
            {
                good = 0;
                break;
            }
        }
        if(good == 1)
        {
            var memory = s[0];
            s[0] = s[index];
            s[index] = memory;
        }

        string = ""
        for(var j = 0; j < len; j++)
        {
            string += s[j];
        }

        result.push(string);
    }
}

for(var i = 0; i < t; i++)
{
    print(result[i]);
}

"use strict";

const mySet = new Set();
const arr = new Array(26).fill(null);

const input = [];
const RL = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
});
RL.on("line", line => {
  input.push(line.trim());
});
RL.on("close", () => {
  const N = +input[0];
  for (let i = 1; i <= N; i += 1) {
    const setSize = isImpossible(input[i]);
    if (setSize === 1) {
      console.log(-1);
      continue;
    }

    initArray();
    solve(input[i]);
  }
});

function isImpossible(str) {
  mySet.clear();
  for (let char of str) {
    mySet.add(char);
  }
  return mySet.size;
}

function initArray() {
  for (let i = 0; i < 26; i += 1) {
    arr[i] = 0;
  }
}

function isPalindrome(str) {
  const shrinked = arr.map(ele => {
    return ele % 2;
  });

  let count = 0;
  shrinked.forEach(ele => {
    if (ele === 1) {
      count += 1;
    }
  });

  if (count >= 2) {
    return false;
  }

  return true;
}

function solve(str) {
  for (let char of str) {
    arr[char.codePointAt(0) - "a".codePointAt(0)] += 1;
  }

  const answer = isPalindrome(arr);
  if (answer === false) {
    console.log(str);
    return;
  }

  let good = "";
  let oddValue = -1;
  let oddIndex = -1;

  arr.forEach((value, index) => {
    if (value === 0) {
      return;
    }

    if (value % 2 === 1) {
      oddValue = value;
      oddIndex = index;
      return;
    }

    const left = good.slice(0, parseInt(good.length / 2));
    const right = good.slice(parseInt(good.length / 2), good.length);
    const middle = String.fromCodePoint(index + "a".codePointAt(0)).repeat(
      value
    );

    good = left + middle + right;
  });

  if (oddIndex !== -1) {
    const left = good.slice(0, parseInt(good.length / 2));
    const right = good.slice(parseInt(good.length / 2), good.length);
    const middle = String.fromCodePoint(oddIndex + "a".codePointAt(0)).repeat(
      oddValue
    );

    good = left + middle + right;
  }

  const temp = good.split("");
  [temp[0], temp[parseInt(temp.length / 2)]] = [
    temp[parseInt(temp.length / 2)],
    temp[0]
  ];
  console.log(`${temp.join("")}`);
}

// NYAN NYAN
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
// ░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
// ░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
// ░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
// ░▄▄▄▄▄░░█░░░░░░▀░░░░▀█░░▀▄░░░░░█▀▀░██░░
// ░██▄▀██▄█░░░▄░░░░░░░██░░░░▀▀▀▀▀░░░░██░░
// ░░▀██▄▀██░░░░░░░░▀░██▀░░░░░░░░░░░░░▀██░
// ░░░░▀████░▀░░░░▄░░░██░░░▄█░░░░▄░▄█░░██░
// ░░░░░░░▀█░░░░▄░░░░░██░░░░▄░░░▄░░▄░░░██░
// ░░░░░░░▄█▄░░░░░░░░░░░▀▄░░▀▀▀▀▀▀▀▀░░▄▀░░
// ░░░░░░█▀▀█████████▀▀▀▀████████████▀░░░░
// ░░░░░░████▀░░███▀░░░░░░▀███░░▀██▀░░░░░░
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

// 백준의 노드 버전이 너무 낮아 babel 사용.
// 풀이는 solve() 함수에 있음.

const CODEFORCES_NODE = "cf";
const CODEFORCES_V8 = "cf-v8";
const BEAKJOON = "bj";
const TEST = "test";
// var SITE = BEAKJOON;
var SITE = CODEFORCES_NODE;
var DEBUG = false;

if(SITE == BEAKJOON){
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(search, pos) {
      return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
  }
  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
      if (this_len === undefined || this_len > this.length) {
        this_len = this.length;
      }
      return this.substring(this_len - search.length, this_len) === search;
    };
  }
  if (!String.prototype.repeat) {
    String.prototype.repeat = function(count) {
      'use strict';
      if (this == null) {
        throw new TypeError('can\'t convert ' + this + ' to object');
      }
      var str = '' + this;
      count = +count;
      if (count != count) {
        count = 0;
      }
      if (count < 0) {
        throw new RangeError('repeat count must be non-negative');
      }
      if (count == Infinity) {
        throw new RangeError('repeat count must be less than infinity');
      }
      count = Math.floor(count);
      if (str.length == 0 || count == 0) {
        return '';
      }
      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28) {
        throw new RangeError('repeat count must not overflow maximum string size');
      }
      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
         str += str;
         count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    }
  }
}

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

Function.prototype.repeat = function(times){
  for(let i = 0; i < times; i++){
    this();
  }
}

Array.prototype.getMaxConsecutiveSum = function(defaultValue = -Infinity){
  const N = this.length;
  let maxsum = defaultValue;
  let cursum = defaultValue;
  let cur;
  for(var ii = 0; ii < N; ii++){
    cur = this[ii];
    if(cursum + cur > 0){
      if(cur > cursum + cur){
        cursum = cur;
      } else cursum += cur;
    } else {
      cursum = cur;
      if(maxsum < cursum){
        maxsum = cursum;
      }
    }
    if(maxsum < cursum){
      maxsum = cursum;
    }
  }
  this.maxConsecutiveSum = maxsum;
  return maxsum;
}

try {
  require('manakin').global;
  // require ("babel-polyfill");
} catch (error) {

}
try {
  process.argv.forEach(function (val, index, array) {
    if (val.startsWith("site")) {
      switch (val.split("=")[1]) {
        case "test":
          // console.log('change site to test')
          SITE = TEST;
          break;
        case "cf-node":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf-v8":
          // console.log('change site to cf')
          SITE = CODEFORCES_V8;
          break;
        case "bj":
          // console.log('change site to bj')
          SITE = BEAKJOON;
          break;
      }
    }
    if (val.startsWith("debug")) {
      switch (val.split("=")[1]) {
        case "true":
          DEBUG = true;
          break;
        case "false":
          DEBUG = false;
          break;
      }
    }
  });
} catch (error) {
}

let inputFilePath = '';
switch(SITE){
  case TEST:
    const config = require('config');
    var fs = require("fs");
    var path = require('path');
    inputFilePath = config.get('INPUTFILEPATH') || path.resolve(__dirname, "input.txt");
    break;
  default:
    inputFilePath = './input.txt';
    break;
}
const INPUTFILEPATH = inputFilePath;

// if (!String.prototype.endsWith) {
// 	String.prototype.endsWith = function(search, this_len) {
// 		if (this_len === undefined || this_len > this.length) {
// 			this_len = this.length;
// 		}
// 		return this.substring(this_len - search.length, this_len) === search;
// 	};
// }
// if (!Array.prototype.includes) {
//   Array.prototype.includes = function (target) {
//     return this.indexOf(target) !== -1
//   }
// }

const newLine = '\n';
var ans;
var inputText = "";
var lineCount = 0;
var lines;
var input;
var readline;
var getlines;
var lineOpen = false;
var readingLine = '';

var clockStart;
var clock;

var print;
print = console.log;
var it;
var step;
function EnableLogging(){
  it = console.info;
  step = console.success;
}
function DisableLogging(){
  it = function it(params) {
    return 0;
  }
  step = it;
}
if (DEBUG) {
  EnableLogging();
  clock = function(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
  }
} else {
  DisableLogging();
}

// prepares test data. to replace line input, assign arrays to lines variable.
function prepareTestData() {
  // it(lines);

  // lines = ['custom line 1', 'custom line 2'];
}

// executes exactly once for both test and run. execution time will be included to elapsed time.
const prepareSolve = () => {

}

function power(x, y) {    //분할 정복을 이용하여 x^y 구하기
  let ret = 1;
  while (y > 0) {
    if (y % 2) {
        ret *= x;
        ret %= P;
    }
    x *= x;
    x %= P;
    y /= 2;
  }
  return ret;
}

function createArray(lengths) {
  var arr = new Array(lengths || 0),
    i = lengths;
  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while (i--) arr[lengths - 1 - i] = createArray.apply(this, args);
  }
  return arr;
}

function numericSortList(list){
  list.sort((a,b)=>a-b);
}

function getRectangleIntersection(r1, r2)
{
    if(r1.x > r2.x+r2.w) return null;
    if(r1.x+r1.w < r2.x) return null;
    if(r1.y > r2.y+r2.h) return null;
    if(r1.y+r1.h < r2.y) return null;

    var rect = {};
    rect.x = Math.max(r1.x, r2.x);
    rect.y = Math.max(r1.y, r2.y);
    rect.w = Math.min(r1.x+r1.w, r2.x+r2.w)-rect.x;
    rect.h = Math.min(r1.y+r1.h, r2.y+r2.h)-rect.y;

    return rect;
}

function getRandomNumber(to, from){
  if(from == undefined){
    return Math.floor(Math.random()*to + 1);
  }
  return Math.floor(Math.random()*(to - from) + from);
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ MAIN SOLVE FUNCTION ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function solve(){
  var cases = readInts()[0];
  it(cases);
  for(var i = 0; i < cases; i++){
    it(i);

    /**
     * @type {string}
     */
    var str = readline();
    it(str);

    var charToCount = {};

    for(var c of str){
      it(c);
      if(charToCount[c]){
        ++charToCount[c];
      } else charToCount[c] = 1;
    }

    if(Object.keys(charToCount).length <= 1){
      print('-1');
      continue;
    }

    var newStr = '';

    Object.keys(charToCount).forEach(function(key) {
      for(var k = 0; k < charToCount[key]; k++){
        it('new char : ' + key)
        newStr += key;
      }
    });

    print(newStr);
  }
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function resetRead(){
  lineCount = 0;
}

function checkMemoryUsage() {
  it(process.memoryUsage());
}

function readOne(separator=' ') {
  if(lineOpen && readingLine != null){
  // if(lineOpen){
    // it(readingLine);
    let splitPos = readingLine.search(separator)

    let ret = readingLine.slice(0, splitPos);
    if(splitPos == -1){
      // it('close');
      ret = readingLine;
      readingLine = '';
      lineOpen = false;
    }
    readingLine = readingLine.substr(splitPos + 1)
    // it(ret, readingLine, splitPos);
    return ret;
  } else {
    readingLine = readline();
    lineOpen = true;
    if(readingLine == null) return '';
    return readOne(separator);
  }
}

function readInts() {
  try {
    lineOpen = false;
    return readline()
      .split(" ")
      .map(x => parseInt(x));
  } catch (error) {
    console.error(error);
    return null;
  }
}

switch (SITE) {
  case TEST:
    var fs = require("fs");
    var path = require('path');
    // input = fs.createReadStream(path.resolve(__dirname, "input.txt"), {
    //   encoding: "utf8"
    // });
    input = fs.createReadStream(INPUTFILEPATH, {
      encoding: "utf8"
    });

    function inputListener(line) {
      console.log(line);
      if(line.startsWith('end')){
        console.log('end');
        closing();
      }
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;

  case CODEFORCES_NODE:
    input = process.stdin;

    function inputListener(line) {
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;
  case BEAKJOON:
    var fs = require('fs');
    if (DEBUG) {
      // input = fs.readFileSync('./input.txt').toString();
      inputText = fs.readFileSync(INPUTFILEPATH).toString();

    } else {
      inputText = fs.readFileSync('/dev/stdin').toString();
    }

    readline = function () {
      lineCount++;
      let line = lines[lineCount - 1];
      if (line)
        return lines[lineCount - 1].trim();
      else return null;
    }

    getlines = function (inputText) {
      lineCount = 0;
      return inputText.split(/\r?\n/);
    }

    // lines = getlines(input);
    closing();
    break;
  default:
    break;
}

function closing() {
  if(DEBUG){
    DisableLogging();
    const prepareClock = clock();
    lines = getlines(inputText);
    prepareSolve();
    const prepareClockElapsedTime = clock(prepareClock);
    EnableLogging();
    prepareTestData();
    solve();
    resetRead();
    console.warn('performance check');
    DisableLogging();
    clockStart = clock();
    // lines = getlines(inputText);
    solve();
    console.warn(`${clock(clockStart) + prepareClockElapsedTime} ms`);
    EnableLogging();
    process.exit();
  } else {
    lines = getlines(inputText);
    prepareSolve();
    solve();
    process.exit();
  }
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (str) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = [...str];
  arr.sort();

  const r = arr.join('');
  const reverseR = arr.reverse().join('');

  if (r === reverseR) {
    console.log(-1);
  }
  else {
    console.log(r);
  }

  c++;
});

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  let l=0;
  let t=0
  rl.on('line', (input) => {
     if(l===t+1)
     {
         return 0
     }
    if (l==0) {
          t=parseInt(input)
        } else {
           let s= input.split('')
           s.sort()
           let isPal = true
           for(let i=0;i<s.length/2&&isPal;i++){
               if(s[i]!==s[s.length-i-1]){
                   console.log(s.join(""))
                   isPal = false
               }
           }
           if(isPal){
               console.log(-1)
           }
}
l++
});

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  let l=0;
  let t=0
  rl.on('line', (input) => {
     if(l === t + 1)
     {
         return 0
     }
    if (l==0) {
          t=parseInt(input)
        } else {
           let s = input.split('')
           s.sort()
               if(s[0] !== s[s.length-1]){
                   console.log(s.join(""))
               } else {
                console.log(-1)
               }
           }
    l++
});

"use strict";

const mySet=new Set();
const arr=new Array(26).fill(null);

const input = [];
const RL = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
});
RL.on("line", line => {
  input.push(line.trim());
});
RL.on("close", () => {
  const N=+input[0];
  for(let i=1; i<=N; i+=1){
    const setSize=isImpossible(input[i]);
    if(setSize===1){
      console.log(-1);
      continue;
    }

    initArray();
    solve(input[i]);
  }
});

function isImpossible(str){
  mySet.clear();
  for(let char of str){
    mySet.add(char);
  }
  return mySet.size;
}

function initArray(){
  for(let i=0; i<26; i+=1){
    arr[i]=0;
  }
}

function isPalindrome(str){
  const shrinked=arr.map(ele=>{
    return ele%2;
  });

  let count=0;
  shrinked.forEach(ele=>{
    if(ele===1){
      count+=1;
    }
  });

  if(count>=2){
    return false;
  }

  return true;
}

function solve(str){
  for(let char of str){
    arr[char.codePointAt(0)-"a".codePointAt(0)]+=1;
  }

  const answer=isPalindrome(arr);
  if(answer===false){
    console.log(str);
  }

  let good="";
  let oddValue=-1;
  let oddIndex=-1;

  arr.forEach((value, index)=>{
    if(value===0){
      return;
    }

    if(value%2===1){
      oddValue=value;
      oddIndex=index;
      return;
    }

    const left=good.slice(0, good.length/2);
    const right=good.slice(good.length/2, good.length);
    const middle=String.fromCodePoint(index+"a".codePointAt(0)).repeat(value);

    good=left+middle+right;
  });

  if(oddIndex!==-1){
    const left=good.slice(0, good.length/2);
    const right=good.slice(good.length/2, good.length);
    const middle=String.fromCodePoint(oddIndex+"a".codePointAt(0)).repeat(oddValue);

    good=left+middle+right;
  }

  const temp=good.split('');
  [temp[0], temp[parseInt(temp.length/2)]]=[temp[parseInt(temp.length/2)], temp[0]];
  console.log(`${temp.join('')}`);
}

"use strict";

const mySet=new Set();
const arr=new Array(26).fill(null);

const input = [];
const RL = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
});
RL.on("line", line => {
  input.push(line.trim());
});
RL.on("close", () => {
  const N=+input[0];
  for(let i=1; i<=N; i+=1){
    const setSize=isImpossible(input[i]);
    if(setSize===1){
      console.log(-1);
      continue;
    }

    initArray();
    solve(input[i]);
  }
});

function isImpossible(str){
  mySet.clear();
  for(let char of str){
    mySet.add(char);
  }
  return mySet.size;
}

function initArray(){
  for(let i=0; i<26; i+=1){
    arr[i]=0;
  }
}

function isPalindrome(str){
  const shrinked=arr.map(ele=>{
    return ele%2;
  });

  let count=0;
  shrinked.forEach(ele=>{
    if(ele===1){
      count+=1;
    }
  });

  if(count>=2){
    return false;
  }

  return true;
}

function solve(str){
  for(let char of str){
    arr[char.codePointAt(0)-"a".codePointAt(0)]+=1;
  }

  const answer=isPalindrome(arr);
  if(answer===false){
    console.log(str);
  }

  let good="";
  let oddValue=-1;
  let oddIndex=-1;

  arr.forEach((value, index)=>{
    if(value===0){
      return;
    }

    if(value%2===1){
      oddValue=value;
      oddIndex=index;
      return;
    }

    const left=good.slice(0, parseInt(good.length/2));
    const right=good.slice(parseInt(good.length/2), good.length);
    const middle=String.fromCodePoint(index+"a".codePointAt(0)).repeat(value);

    good=left+middle+right;
  });

  if(oddIndex!==-1){
    const left=good.slice(0, parseInt(good.length/2));
    const right=good.slice(parseInt(good.length/2), good.length);
    const middle=String.fromCodePoint(oddIndex+"a".codePointAt(0)).repeat(oddValue);

    good=left+middle+right;
  }

  const temp=good.split('');
  [temp[0], temp[parseInt(temp.length/2)]]=[temp[parseInt(temp.length/2)], temp[0]];
  console.log(`${temp.join('')}`);
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (str) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = [...str];
  arr.sort();

  const r = arr.join('');

  if (r === str) {
    console.log(-1);
  }
  else {
    console.log(r);
  }

  c++;
});

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  let l=0;
  let t=0
  rl.on('line', (input) => {
     if(l===t+1)
     {
         return 0
     }
    if (l==0) {
          t=parseInt(input)
        } else {
           rl.close();
           let s= input.split('')
           s.sort()
           let isPal = true
           for(let i=0;i<s.length/2&&isPal;i++){
               if(s[i]!==s[s.length-i-1]){
                   console.log(s.join(""))
                   isPal = false
               }
           }
           if(isPal){
               console.log(-1)
           }
}
l++
});

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  let l=0;
  let t=0
  rl.on('line', (input) => {
     if(l===t+1)
     {
         return 0
     }
    if (l==0) {
          t=parseInt(input)
        } else {
           rl.close();
           let s= input.split('')
           s.sort()
           let isPal = true
           for(let i=0;i<s.length/2;i++){
               if(s[i]!==s[s.length-i-1]){
                   console.log(s.join(""))
                   isPal = false
               }
           }
           if(isPal){
               console.log(-1)
           }
}
l++
});

'use strict'

var a = parseInt(readline());
var i=0;
var arr=[];
for(i;i<a;i++){
    arr[i]=readline();
}

function hwbh(a){
    var p=0;
    var i=0;
    var n='';
    for(i in a){
        if(a[i]!==a[0]){
            p=i;
            break;
        }
    }
    if(p==0){
        print('-1');
    }else{
        n=a[0];
        a[0]=a[p];
        a[p]=n;
        print(a.join(''));
    }

}
var j;
var p;
for(i in arr){
    p=0;
    for(j=0;j<=(arr[i].length-1)/2;j++){
        if(arr[i].length==1){
            print('-1');
            continue;
        }else if(arr[i][j]!==arr[i][arr[i].length-j-1]){
            p=1;
        }

    }
    if(p==1){
        print(arr[i]);
    }else
        hwbh(arr[i].split(''));
}

var t = function () {
    var input = readline();
    return parseInt(input);
} ();

for(var i=0; i<t; i++) {
    var line = readline();

    var good = "";

    var possible = false;
    for(var j=1; j<line.length; j++) {
        if( line[0] != line[j] ) {
            possible = true;
            other = j;
            break;
        }
    }
    if( possible === false ) {
        print(-1);
    } else {
        if(j==1) {
            print(line)
        } else {
            print( line[0] + line.substr(1, j-1) + line.substr(j+1) + line[j] )
        }
    }

}

var t = function () {
    var input = readline();
    return parseInt(input);
} ();

for(var i=0; i<t; i++) {
    var line = readline();

    var good = "";

    var possible = false;
    for(var j=1; j<line.length; j++) {
        if( line[0] != line[j] ) {
            possible = true;
            other = j;
            break;
        }
    }
    if( possible === false ) {
        print(-1);
    } else {
        if(j==1) {
            print(line)
        } else {
            print( line[0] + line[j] + line.substr(1, j-1) + line.substr(j+1))
        }
    }

}

var t = parseInt(readline())
var result = []

for(var i = 0; i < t; i++)
{
    var str = readline();
    var s = []
    var len = s.length;

    for(var j = 0; j < len; j++)
    {
        s.push(str[j]);
    }

    var same = 1;
    var good = 1;

    for(j = 0; j < len; j++)
    {
        if(s[j] != s[0])
        {
            same = 0;
            index = j;
            break;
        }
    }
    if(same == 1)
    {
        result.push("-1");
    }
    else
    {
        for(var j = 0; j < len; j++)
        {
            if(s[j] != s[length - 1 - j])
            {
                good = 0;
                break;
            }
        }
        if(good == 1)
        {
            var memory = s[0];
            s[0] = s[index];
            s[index] = memory;
        }

        string = ""
        for(var j = 0; j < len; j++)
        {
            string += s[j];
        }

        result.push(string);
    }
}

for(var i = 0; i < t; i++)
{
    print(result[i]);
}

//var input = readline()
var k = readline()

for(var i=0; i<k; i++){
    var n = readline()

    var m = n.split('').sort().join('')

    // var L = Math.ceil(n.length/2)-1
    // var middle = n[L]
    // var first = n[0]
    // //print(first +' '+ middle)

    // arr.splice(0,1,middle)
    // arr.splice(L,1,first)
    // var change = arr.join('')
    // //print(change)

    // var a = n.split("").reverse().join("")
     var c = /^(.)\1+$/.test(n) // check input same letter
    // //print(c)

     if(c) print(-1)
    // else if(n == a) print(change)
     else print (n)

}

//var input = readline()
var k = readline()

for(var i=0; i<k; i++){
    var n = readline()
    var ar = n
    var arr = ar.split('')

    var L = Math.ceil(n.length/2)-1
    var middle = n[L]
    var first = n[0]
    //print(first +' '+ middle)

    arr.splice(0,1,middle)
    arr.splice(L,1,first)
    var change = arr.join('')
    //print(change)

    var a = n.split("").reverse().join("")
    var c = /^(.)\1+$/.test(n) // check input same letter

    if(c) print(-1)
    else if(n == a) print(change)
    else print (n)

}