Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.

Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.

var input = Number(readline());

if(input == 3) {
  print("1 1 1");
}

else if(input>3) {
  if((input-3)%3 == 0) {
    print("2 2 " +(input-4));
  }
  else {
    print("1 2 "+ (input-3));
  }
}

function func(){
	var n = parseInt(readline());
	var x = (n-2)%3?1:2;
	// console.log(1,x,n-x-1);
	print(1,x,n-x-1);
}
func();

// var n = 233;
function func(){
	var n = parseInt(readline());
	var x = Math.floor(n/3);
	var y = n%3;
	var t = x%3;
	var a,b,c;
	if(x === 1){
		if(y === 0){
			a = b = c = x;
		}else if(y === 1){
			a = b = x;
			c = x+y;
		}else {
			a = x;
			b = c = x+1;
		}
	}else {
		if(t===0){
			if(y === 1){
				a = x-1;
				b = c = x+1;
			}else{
				a = b = x-1;
				c = x+y+2;
			}
		}else if(t===1){
			if(y === 1){
				a = b = x;
				c = x+y;
			}else{
				a = x;
				b = c = x+y/2;
			}
		}else {
			if(y === 1){
				a = b = x-1;
				c = x+y+2;
			}else{
				a = b = x;
				c = x+y;
			}
		}
	}
	print(a,b,c);
	// console.log(a,b,c)
}
func();

function main(){
    var n = parseInt(readline());
    var result = "";
    var item = parseInt(n/3);
    var adjust = n % 3;

    if((item + adjust) % 3 === 0){
        if( item % 3 === 0){
            result = (item + 2) + " " + (item - 1) + " " + (item + adjust - 1)
        }else{
            result = item + " " + ( item + 3 - adjust )+ " " + (item + 2 * adjust - 3)
        }
    }else{
        if( item % 3 === 0){
            result = (item + 1) + " " + (item - 1) + " " + (item + adjust)
        }else{
            result = item + " " + item + " " + (item + adjust)
        }
    }
    print(result)
}

main()

var x = parseInt(readline());

switch (x % 3) {
    case 2:
        print(1, 2, x - 3);
        break;
    default:
        print(1, 1, x - 2);
        break;
}

function main() {
  const cin = new Scanner();
  let n = cin.nextInt() - 1;
  let a = 1, b = Math.trunc(n / 2), c = Math.ceil(n / 2);
  if (b % 3 === 0 || c % 3 === 0) {
    b -= 1;
    c += 1;
  }

  console.log(a, b, c);
}

/*
 *  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 = Number) {
    const array = this.nextLine().split(' ');
    if (fn !== String)
      array.forEach((item, index, arr) => { arr[index] = fn(item); });
    return array;
  }

  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').createInterface({input: process.stdin})
const assert = require('assert')

let n, x, y, z
readline.on('line', line => {
    n = parseInt(line)
    if (n == 3) {
        [x, y, z] = [1, 1, 1]
    } else if (n % 3 == 0) {
        [x, y, z] = [1, 4, n - 5]
    } else {
        [x, y, z] = [1, 2, n - 3]
    }
    console.log(`${x} ${y} ${z}`)
})

//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↑入力 ↓出力');
	Main();
});
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 N = nextInt();
	if(N % 3 == 2){
		myout((N - 3) + " 2 1");
	}else{
		myout((N - 2) + " 1 1");
	}
}

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

rl.on('line', (d) => {
  let n = +d;
  let a = 1;
  let b = Math.floor((n - 1) / 2);
  let c = Math.ceil((n - 1) / 2);

  while (b % 3 === 0 || c % 3 === 0) {
    b--;
    c++;
  }

  console.log(a, b, c);
});

var cnt = 0;
process.stdin.addListener("data", function(d) {
	var s = d.toString().trim();
	var x = parseInt(s);
	if( x%3 === 0){
        process.stdout.write(x-2+' 1 1');
    }
	else {
        //if(x==3) process.stdout.write('1 1 1');
         process.stdout.write(x-3+' 1 2');

        }
            cnt++;
    if(cnt > 0) process.exit();
   // process.exit();
});

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

let l = 0;
let hand = []
rl.on('line', (input) => {
    if (l === 0) {
        rl.close();
        let n = parseInt(input)
        if((n-2)%3===0)
         console.log(1,2,n-3)
         else
         console.log(1,1,n-2)
    }
})

var a = Number(readline());
print(1);
if ((a-1)%3 === 0){
    print (1);
    print (a-2);
} else {
    print (2);
    print (a-3);
}

var a = readline();
print(1);
if ((a-1)%3 === 0){
    print (1);
    print (a-2);
} else {
    print (2);
    print (a-3);
}

	var n=parseInt(readline());
	if(n%3===0){print (n/3+" "+n/3+" "+n/3);}
	else{print (Math.floor(n/3)+" "+Math.floor(n/3)+" "+ (n-((Math.floor(n/3))*2)) );}

var input = Number(readline());

if((input%3) == 0) {
  var ans = input/3;
  if(ans%3 != 0) {
    print(ans +" "+ans+ " "+ ans);
  }
  else {
    print((ans+1) +" "+ (ans+1) +" "+(ans-2));
  }

}
else {
  var rem = input%3;
  ans = Math.floor(input/3);
  print((ans +" "+ ans +" "+ (ans+rem)));
}

// var n = 233;
function func(){
	var n = parseInt(readline());
	var x = Math.floor(n/3);
	var y = n%3;
	var t = x%3;
	var a,b,c;
	if(x === 1){
		if(y === 0){
			a = b = c = x;
		}else if(y === 1){
			a = b = x;
			c = x+y;
		}else {
			a = x;
			b = c = x+1;
		}
	}else {
		if(t===0){
			if(y === 1){
				a = x-1;
				b = c = x+1;
			}else{
				a = b = x-1;
				c = x+y+2;
			}
		}else if(t===1){
			if(y === 1){
				a = b = x;
				c = x+y;
			}else{
				a = x;
				b = c = x+1;
			}
		}else {
			if(y === 1){
				a = b = x-1;
				c = x+y+2;
			}else{
				a = b = x;
				c = x+y;
			}
		}
	}
	print(a,b,c);
	// console.log(a,b,c)
}
func();

// var n = 233;
function func(n){
	var n = parseInt(readline());
	var x = Math.floor(n/3);
	var y = n%3;
	var t = x%3;
	var a,b,c;
	if(x === 1){
		if(y === 0){
			a = b = c = x;
		}else if(y === 1){
			a = b = x;
			c = x+y;
		}else {
			a = x;
			b = c = x+1;
		}
	}else {
		if(t===0){
			if(y === 1){
				a = x-1;
				b = c = x+1;
			}else{
				a = b = x-1;
				c = x+y+2;
			}
		}else if(t===1){
			if(y === 1){
				a = b = x;
				c = x+y;
			}else{
				a = b = x;
				c = x+y;
			}
		}else {
			if(y === 1){
				a = b = x-1;
				c = x+y+2;
			}else{
				a = b = x;
				c = x+y;
			}
		}
	}
	print(a,b,c);
}
func();

function main(){
    var n = parseInt(readline());
    var result = "";
    var item = parseInt(n/3);
    var adjust = n % 3;
    if( item % 3 === 0){
        result = (item - 1) + " "+(item +1) + " " + (item + adjust)
    }else if((item + adjust) % 3 === 0){
        result = item + " " + ( item + 3 - adjust )+ " " + (item + 2 * adjust - 3)
    }else{
        result = item + " " + item + " " + (item + adjust)
    }
    print(result)
}

main()

var str = readline();
//var str = 387420489;
var num = Math.round(str / 3);
//alert(str + " " + num)
var salida;
var cantidadSumar = str - (num * 3);
//alert(cantidadSumar);

if (valido(num) == 1 && valido(num + cantidadSumar) == 1) {
//    alert("1")
    salida = num + " " + num + " " + (num + cantidadSumar);
} else if (valido(num) == -1 && cantidadSumar!=0) {
//    alert("2")
    num = num + cantidadSumar;
    cantidadSumar = str - (num * 3);
    salida = num + " " + num + " " + (num + cantidadSumar);
} else if (valido(num) == -1 && cantidadSumar == 0) {
//    alert("3")
    salida = (num+1) + " " + (num+1) + " " + (num-2);
}

function valido(num) {
    if (num % 3 == 0) {
        return -1//No es válido
    } else return 1;
}

print(salida)

var str = readline();
//var str = 1234;
var numCercano = Math.round(str / 3);
while (divisible(numCercano) == -1) {
    numCercano++;
}
var n1 = n2 = n3 = numCercano;
if (numCercano * 3 != str) {
    var numSuma = str - (n1 + n2 + n3);
    if (divisible(n1 + numSuma) == 1) {
        n1 += numSuma;
    }
}
    function divisible(num) {
        if (num % 3 == 0) {
            return -1//No es válido
        } else return 1;
    }

print(n1 + " " + n2 + " " + n3)

var str = readline();
//var str = 233;
var numCercano = Math.round(str / 3);
while (divisible(numCercano)==-1) {
    numCercano--;
}
var n1 = n2 = n3 = numCercano;
var numSuma = str - (n1+n2+n3);
if (divisible(n1+numSuma)==1) {
    n1 += numSuma;
}

function divisible(num) {
    if (num % 3 == 0) {
        return -1//No es válido
    } else return 1;
}

print(n1 + " " + n2 + " " + n3)

var str = readline();
//var str = 233;
var num = Math.round(str / 3);
//alert(str + " " + num)
var salida;
var cantidadSumar = str - (num * 3);
//alert(cantidadSumar);

if (valido(num)==1 && valido(num+cantidadSumar)==1) {
    salida = num + " " + num + " " + (num + cantidadSumar);
} else if (valido(num) == -1) {
    num = num + cantidadSumar;
    cantidadSumar = str - (num * 3);
    salida = num + " " + num + " " + (num+cantidadSumar);
}

function valido(num) {
    if (num % 3 == 0) {
        return -1//No es válido
    } else return 1;
}

print(salida)

var str = readline();
//var str = 7;
var div = Math.floor(str / 3);
var num = div * 3;
if (str==num) {
    salida = div + " " + div + " " + div;
} else {
    if (str-num==1) {
        salida = (div+1) + " " + div + " " + div;
    } else {
        salida = (div+2) + " " + div + " " + div;
    }
}

print(salida)

var str = readline();
//var str = 10;
var num = Math.round(str / 3);
var salida;

if (valido(num)==1 && num*3==str) {//valido y suma bien
    salida = num + " " + num + " " + num;
} else if (valido(num) == -1 && num * 3 ==str) {//no es valido pero suma bien
    salida = (num+1) + " " + (num+1) + " " + (num-2);
} else if (valido(num) == -1 && num * 3 != str) {//No es valido pero no suma bien
    if ((num*3)+1==str) {
        salida = (num+1) + " " + (num) + " " + (num);
    } else if((num * 3) + 2 == str) {
        salida = (num+2) + " " + (num) + " " + (num);
    }

}

function valido(num) {
    if (num % 3 == 0) {
        return -1//No es válido
    } else return 1;
}

print(salida)

function main() {
  const cin = new Scanner();
  let n = cin.nextInt() - 1;
  let a = 1, b = Math.trunc(n / 2), c = b;
  if (b % 3 === 0) {
    b -= 1;
    c += 1;
  }

  console.log(a, b, c);
}

/*
 *  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 = Number) {
    const array = this.nextLine().split(' ');
    if (fn !== String)
      array.forEach((item, index, arr) => { arr[index] = fn(item); });
    return array;
  }

  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(); });

function main() {
  const cin = new Scanner();
  let n = cin.nextInt() - 1;
  let a = 1, b = Math.trunc(n / 2), c = Math.ceil(n / 2);
  if (b % 3 === 0) {
    b -= 1;
    c += 1;
  }

  console.log(a, b, c);
}

/*
 *  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 = Number) {
    const array = this.nextLine().split(' ');
    if (fn !== String)
      array.forEach((item, index, arr) => { arr[index] = fn(item); });
    return array;
  }

  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(); });

//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↑入力 ↓出力');
	Main();
});
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 N = nextInt();
	var single = Math.floor(N / 3);
	var second = single + (N % 3);
	myout(single + " " + single + " " + second);
}

var cnt = 0;
process.stdin.addListener("data", function(d) {
	var s = d.toString().trim();
	var x = parseInt(s);
	if( x%2 == 0){
        process.stdout.write(x-2+' 1 1');
    }
	else {
        process.stdout.write(x-3+' 1 2');

        }
            cnt++;
    if(cnt > 0) process.exit();
   // process.exit();
});

var cnt = 0;
process.stdin.addListener("data", function(d) {
	var s = d.toString().trim();
	var x = parseInt(s);
	if( x%2 === 0){
        process.stdout.write(x-2+' 1 1');
    }
	else {
        if(x==3) process.stdout.write('1 1 1');
        else process.stdout.write(x-3+' 1 2');

        }
            cnt++;
    if(cnt > 0) process.exit();
   // process.exit();
});

var cnt = 0;
process.stdin.addListener("data", function(d) {
	var s = d.toString().trim();
	var x = parseInt(s);
	if( x%3 == 0){
        process.stdout.write(x-2+' 1 1');
    }
	else {
        //if(x==3) process.stdout.write('1 1 1');
         process.stdout.write(x-2+' 1 1');

        }
            cnt++;
    if(cnt > 0) process.exit();
   // process.exit();
});


Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.

5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

var n = readline().trim();

var id = 0;
var olduser = new Array();
var newuser = new Array();
var users = new Array();

for (var i = 0; i < n; i++) {
    var line = readline().split(' ');
    if (users[line[0]] === undefined) {
        users[line[0]] = id;
        olduser[id] = line[0];
        id++;
    }
    var tempid = users[line[0]];
    line[0] = undefined;
    users[line[1]] = tempid;
    newuser[tempid] = line[1];
}
print(id);
for (var i = 0; i < id; i++) {
    print(olduser[i] + ' ' + newuser[i]);
}

var n = +readline();

var users = {};
var seen = {};

var lookup = {};

for(var i = 0; i < n; i++) {
    var req = readline().split(" ");
    var prev = req[0];
    var next = req[1];

    if(!(prev in seen)) {
        users[prev] = next;
        lookup[next] = prev;
    } else {
        var user = lookup[prev];
        users[user] = next;
        lookup[next] = user;
    }
    seen[prev] = true;
    seen[next] = true;
}

print(Object.keys(users).length);
for(var k in users) {
    print(k+" "+users[k]);
}

var n = parseInt(readline());

var map = new Map();

while (n-->0) {
  var line = readline().split(' ');
  if (map.has(line[0])) {
    var old = map.get(line[0]);
    map.set(line[1], old);
    map.delete(line[0]);
  } else {
    map.set(line[1], line[0]);
  }
}

write(map.size+'\n');

map.forEach((value, key) => {
    write(value + ' ' + key + '\n');
  },
  map);

var n = parseInt(readline());

var map = new Map();

while (n-- > 0) {
    var line = readline().split(" ");
    var old_handle = line[0];
    var new_handle = line[1];

    if (map.has(old_handle)) {
        map.set(new_handle, map.get(old_handle));
        map.delete(old_handle);
    } else {
        map.set(new_handle, old_handle);
    }
}

write(map.size + "\n");

map.forEach((v, k) => {
    write(v + " " + k + "\n");
}, map);

var app = {
    changedHandleCount : 0,
    oldNewHandleMap : {},
    result : [],
    main : function()    {
        this.initialize();
        this.readValues();
        this.sovleResult();
        this.printResult();
    },
    initialize : function()    {
        app.result = [];
        app.oldNewHandleMap = {};
    },
    readValues : function()    {
        app.changedHandleCount = parseInt(readline());
    },
    sovleResult : function()    {
        for(var index = 0; index < app.changedHandleCount; index++)    {
            var oldAndNewHanlde = readline().split(/\s/),
                oldHandle = oldAndNewHanlde[0],
                newHandle = oldAndNewHanlde[1];

            if(app.oldNewHandleMap[oldHandle])  {
                var tempSavedHandle = app.oldNewHandleMap[oldHandle];
                delete app.oldNewHandleMap[oldHandle];
                app.oldNewHandleMap[newHandle] = tempSavedHandle;
            } else  {
                app.oldNewHandleMap[newHandle] = oldHandle;
            }
        }
    },
    printResult : function()    {
        var newHandleList = Object.keys(app.oldNewHandleMap);

        print(newHandleList.length);

        newHandleList.forEach(function(newHandle)    {
            print(app.oldNewHandleMap[newHandle] + ' ' + newHandle);
        });
        // print(this.result);
    }
};

app.main();

"use strict";

var _slicedToArray = (function() {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;
    try {
      for (
        var _i = arr[Symbol.iterator](), _s;
        !(_n = (_s = _i.next()).done);
        _n = true
      ) {
        _arr.push(_s.value);
        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
  return function(arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError(
        "Invalid attempt to destructure non-iterable instance"
      );
    }
  };
})();

var compose = function compose() {
  for (
    var _len = arguments.length, functions = Array(_len), _key = 0;
    _key < _len;
    _key++
  ) {
    functions[_key] = arguments[_key];
  }

  return function() {
    for (
      var _len2 = arguments.length, args = Array(_len2), _key2 = 0;
      _key2 < _len2;
      _key2++
    ) {
      args[_key2] = arguments[_key2];
    }

    return functions.reduce(function(currArgs, func) {
      return func(currArgs);
    }, args);
  };
};

var lineToStringArray = function lineToStringArray(str) {
  return str.split(" ");
};
var lineToNumberArray = function lineToNumberArray(str) {
  return lineToStringArray(str).map(function(num) {
    return parseInt(num, 10);
  });
};

var readNumbersLine = compose(
  readline,
  lineToNumberArray
);
var readStringsLine = compose(
  readline,
  lineToStringArray
);

var _readNumbersLine = readNumbersLine(),
  _readNumbersLine2 = _slicedToArray(_readNumbersLine, 1),
  n = _readNumbersLine2[0];

var map = Object.create(null);
var oldNames = [];

for (var i = 0; i < n; i++) {
  var _readStringsLine = readStringsLine(),
    _readStringsLine2 = _slicedToArray(_readStringsLine, 2),
    oldName = _readStringsLine2[0],
    newName = _readStringsLine2[1];

  map[oldName] = newName;
  oldNames.push(oldName);
}

var res = [];

var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (
    var _iterator = oldNames[Symbol.iterator](), _step;
    !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
    _iteratorNormalCompletion = true
  ) {
    var _oldName = _step.value;

    var _newName = map[_oldName];
    delete map[_oldName];
    while (map[_newName]) {
      var _oldName3 = _newName;
      _newName = map[_newName];
      delete map[_oldName3];
    }
    if (_newName) res.push([_oldName, _newName]);
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

print(res.length);

var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;

try {
  for (
    var _iterator2 = res[Symbol.iterator](), _step2;
    !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
    _iteratorNormalCompletion2 = true
  ) {
    var _ref = _step2.value;

    var _ref2 = _slicedToArray(_ref, 2);

    var _oldName2 = _ref2[0];
    var _newName2 = _ref2[1];

    print(_oldName2, _newName2);
  }
} catch (err) {
  _didIteratorError2 = true;
  _iteratorError2 = err;
} finally {
  try {
    if (!_iteratorNormalCompletion2 && _iterator2.return) {
      _iterator2.return();
    }
  } finally {
    if (_didIteratorError2) {
      throw _iteratorError2;
    }
  }
}

var n = +readline();

var users = {};
var seen = {};

var lookup = {};

for(var i = 0; i < n; i++) {
    var req = readline().split(" ");
    var prev = req[0];
    var next = req[1];

    if(!(prev in seen)) {
        users[prev] = next;
        lookup[next] = prev;
    } else {
        var user = lookup[prev];
        users[user] = next;
        lookup[next] = user;
    }
    seen[prev] = true;
}

print(Object.keys(users).length);
for(var k in users) {
    print(k+" "+users[k]);
}

"use strict";

var _slicedToArray = (function() {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;
    try {
      for (
        var _i = arr[Symbol.iterator](), _s;
        !(_n = (_s = _i.next()).done);
        _n = true
      ) {
        _arr.push(_s.value);
        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
  return function(arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError(
        "Invalid attempt to destructure non-iterable instance"
      );
    }
  };
})();

var compose = function compose() {
  for (
    var _len = arguments.length, functions = Array(_len), _key = 0;
    _key < _len;
    _key++
  ) {
    functions[_key] = arguments[_key];
  }

  return function() {
    for (
      var _len2 = arguments.length, args = Array(_len2), _key2 = 0;
      _key2 < _len2;
      _key2++
    ) {
      args[_key2] = arguments[_key2];
    }

    return functions.reduce(function(currArgs, func) {
      return func(currArgs);
    }, args);
  };
};

var lineToNumberArray = function lineToNumberArray(str) {
  return str.split(" ").map(function(num) {
    return parseInt(num, 10);
  });
};

var readNumbersLine = compose(
  readline,
  lineToNumberArray
);

var _readNumbersLine = readNumbersLine(),
  _readNumbersLine2 = _slicedToArray(_readNumbersLine, 3),
  n = _readNumbersLine2[0],
  t = _readNumbersLine2[1],
  c = _readNumbersLine2[2];

var arr = readNumbersLine();
var lastTOver = -1;
var res = 0;

var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (
    var _iterator = arr.entries()[Symbol.iterator](), _step;
    !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
    _iteratorNormalCompletion = true
  ) {
    var _ref = _step.value;

    var _ref2 = _slicedToArray(_ref, 2);

    var key = _ref2[0];
    var value = _ref2[1];

    if (value > t) lastTOver = key;
    if (key - lastTOver >= c) res++;
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

print(res);


Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1) + pos(ai2) + ... + pos(aim) for the i-th customer.When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.Your task is to calculate the total time it takes for Ayush to process all the orders.You can assume that the market has endless stock.

The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market. The next line contains k distinct integers pl (1 ≤ pl ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k. Each of the next n lines contains m distinct integers aij (1 ≤ aij ≤ k) — the order of the i-th person.

Print the only integer t — the total time needed for Ayush to process all the orders.

NoteCustomer 1 wants the items 1 and 5.pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5].pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2].Time taken for the first customer is 3 + 5 = 8.Customer 2 wants the items 3 and 1.pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2].pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2].Time taken for the second customer is 3 + 3 = 6.Total time is 8 + 6 = 14.Formally pos(x) is the index of x in the current row.

(function () {
    var line = readline();
    var lines = [line.split(' ')];
    while (line) {
        line = readline();
        if (line) {
            lines.push(line.split(' '));
        }
    }

    var items = lines[1];
    var time = 0;

    function pos(item) {
        return items.indexOf(item);
    }

    for (var i = 2, k = lines.length; i < k; i++) {
        lines[i].forEach(function (item) {
            var itemPos = pos(item);
            items.splice(itemPos, 1);
            items.unshift(item);
            time += itemPos + 1;
        });
    }

    print(time)
})();

(function () {
    var line = readline();
    var lines = [line.split(' ')];
    while (line) {
        line = readline();
        if (line) {
            lines.push(line.split(' '));
        }
    }

    var items = lines[1];
    var time = 0;

    print(items);

    function pos(item) {
        return items.indexOf(item);
    }

    for (var i = 2, k = lines.length; i < k; i++) {
        lines[i].forEach(function (item) {
            var itemPos = pos(item);
            items.splice(itemPos, 1);
            items.unshift(item);
            time += itemPos + 1;
        });
    }

    print(time)
})();


Black is gifted with a Divine array $$$a$$$ consisting of $$$n$$$ ($$$1 \le n \le 2000$$$) integers. Each position in $$$a$$$ has an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable transformation.The transformation consists of infinite steps. Array $$$a$$$ changes at the $$$i$$$-th step in the following way: for every position $$$j$$$, $$$a_j$$$ becomes equal to the number of occurrences of $$$a_j$$$ in $$$a$$$ before starting this step.Here is an example to help you understand the process better:  Initial array:$$$2$$$ $$$1$$$ $$$1$$$ $$$4$$$ $$$3$$$ $$$1$$$ $$$2$$$After the $$$1$$$-st step:$$$2$$$ $$$3$$$ $$$3$$$ $$$1$$$ $$$1$$$ $$$3$$$ $$$2$$$After the $$$2$$$-nd step:$$$2$$$ $$$3$$$ $$$3$$$ $$$2$$$ $$$2$$$ $$$3$$$ $$$2$$$After the $$$3$$$-rd step:$$$4$$$ $$$3$$$ $$$3$$$ $$$4$$$ $$$4$$$ $$$3$$$ $$$4$$$...... In the initial array, we had two $$$2$$$-s, three $$$1$$$-s, only one $$$4$$$ and only one $$$3$$$, so after the first step, each element became equal to the number of its occurrences in the initial array: all twos changed to $$$2$$$, all ones changed to $$$3$$$, four changed to $$$1$$$ and three changed to $$$1$$$.The transformation steps continue forever.You have to process $$$q$$$ queries: in each query, Black is curious to know the value of $$$a_x$$$ after the $$$k$$$-th step of transformation.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the initial values of array $$$a$$$. The third line of each test case contains a single integer $$$q$$$ ($$$1 \le q \le 100\,000$$$) — the number of queries. Next $$$q$$$ lines contain the information about queries — one query per line. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$k_i$$$ ($$$1 \le x_i \le n$$$; $$$0 \le k_i \le 10^9$$$), meaning that Black is asking for the value of $$$a_{x_i}$$$ after the $$$k_i$$$-th step of transformation. $$$k_i = 0$$$ means that Black is interested in values of the initial array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2000$$$ and the sum of $$$q$$$ over all test cases doesn't exceed $$$100\,000$$$.

For each test case, print $$$q$$$ answers. The $$$i$$$-th of them should be the value of $$$a_{x_i}$$$ after the $$$k_i$$$-th step of transformation. It can be shown that the answer to each query is unique.

"use strict";

//..................................import for reading input...................................//
  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.split("\n");
    main();
  });
  function readline() {
    return inputString[currentLine++];
  }
//............................................................................................//

function main() {
  let t = +(readline());
  while (t--) {
    solution();
  }
}

function solution() {
  let n = +(readline());
  let divineArray = readline().split(' ').map((item) => +item);
  let derivativeArray = transformArray(n, divineArray);

  let allPossibleTransformations = [];
  let stopAt = 0;
  allPossibleTransformations[stopAt++] = divineArray;

  while( divineArray.join(' ') !== derivativeArray.join(' ') ) {
    divineArray = derivativeArray;
    allPossibleTransformations[stopAt++] = divineArray;
    derivativeArray = transformArray(n, divineArray);
  }

  let q = +(readline());
  while (q--) {
    let [x, k] = readline().split(' ').map((item) => +item);
    k = (k > stopAt-1) ? stopAt-1 : k;
    console.log(allPossibleTransformations[k][x-1]);
  }
}

function transformArray(n, divineArray) {
  let counterArray = new Array(n+1).fill(0);
  let newArray = [];
    for (let i = 0; i < n; i++) {
    counterArray[divineArray[i]]++;
  }
  for (let i = 0; i < n; i++) {
    newArray[i] = counterArray[divineArray[i]];
  }

  return newArray;
}

const solve = (n,arr,q)=>{
     let query = [];
     query.push(arr);
     for(let i=1;i<=n;i++){
          let t = query[i-1],obj = {};
          for(let i=0;i<n;i++){
               if(obj[t[i]]) obj[t[i]]++;
               else obj[t[i]] = 1;
          }
          let newA= [];
          for(let i=0;i<n;i++) newA.push(obj[t[i]]);
          query.push(newA);
     }
     for(let i=0;i<q.length;i++){
          if(q[i][1]>=n) console.log(query[n][q[i][0]-1]);
          else console.log(query[q[i][1]][q[i][0]-1]);
     }
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr =  readline().trim().split(" ").map(cur=>parseInt(cur));
       let qn = parseInt(readline());
       let q = [];
       for(let i=0;i<qn;i++){
            q.push(readline().trim().split(" ").map(cur=>parseInt(cur)));
       }
       solve(n,arr,q);
  }
}
main();

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
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';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//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();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = {};
		map[0] = makeClone(list);
		var max = 0;
		for(var i = 0; i < N; i++){
			var isChange = false;
			var count = getCountMap(list);
			for(var j = 0; j < N; j++){
				if(list[j] != count[list[j]]){
					isChange = true;
				}
				list[j] = count[list[j]];
			}
			map[i + 1] = makeClone(list);
			max++;
			if(!isChange){
				break;
			}
		}
		var Q = nextInt();
		for(var i = 0; i < Q; i++){
			var x = nextInt() - 1;
			var k = Math.min(nextInt(), max);
			myout(map[k][x]);
		}
	}
}


You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays:   $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$;  $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$;  and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j < 0$$$. If there are no $$$j$$$ such that $$$p_j < 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$) — the initial array $$$a$$$. The third line of each testcase contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$0 \le l_i \le 1$$$), where $$$l_i = 0$$$ means that the position $$$i$$$ is unlocked and $$$l_i = 1$$$ means that the position $$$i$$$ is locked.

Print $$$n$$$ integers — the array $$$a$$$ after the rearrangement. Value $$$k$$$ (the maximum $$$j$$$ such that $$$p_j < 0$$$ (or $$$0$$$ if there are no such $$$j$$$)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them.

NoteIn the first testcase you can rearrange all values however you want but any arrangement will result in $$$k = 0$$$. For example, for an arrangement $$$[1, 2, 3]$$$, $$$p=[1, 3, 6]$$$, so there are no $$$j$$$ such that $$$p_j < 0$$$. Thus, $$$k = 0$$$.In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.In the third testcase the prefix sums for the printed array are $$$p = [-8, -14, -13, -9, -5, 2, 0]$$$. The maximum $$$j$$$ is $$$5$$$, thus $$$k = 5$$$. There are no arrangements such that $$$k < 5$$$.In the fourth testcase $$$p = [-4, -4, -3, 3, 6]$$$.In the fifth testcase $$$p = [-1, 3, 10, 2, 12, 11]$$$.

function solv() {

    var x = parseInt(readline())

    var s = readline().split(' ').map(x => parseInt(x))
    var z = readline().split(' ').map(x => parseInt(x))

    var v = []
    for (var n = 0; n < x; n++) {
        if (z[n] == 0) v.push(s[n])
    }
    v.sort((a, b) => { return b - a })
    var id = 0;
    var res = ''
    for (var n = 0; n < x; n++) {
        if (z[n] == 0) s[n] = v[id++];
        res += s[n] + ' ';
    }
    print(res)
}

var tc = 1;
tc = parseInt(readline());
while (tc--) solv()

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++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
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);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  let t = +readLine();

  while (t--) {
    const len = +readLine();
    let arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let indicator = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let store = [];

    for (let i = 0; i < len; i++) {
      if (indicator[i] === 0) {
        store.push(arr[i]);
        arr[i] = Infinity;
      }
    }

    store.sort((a, b) => b - a);

    for (let i = 0, j = 0; i < len; i++) {
      if (arr[i] === Infinity) {
        arr[i] = store[j];
        j++;
      }
    }

    console.log(arr.join(" "));
  }
}

'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 main() {
  const t = parseInt(readline());
  for (var i=0; i<t; i++) {
    const n = parseInt(readline());
    const a = readline().split(" ").map(x => parseInt(x));
    const locked = readline().split(" ").map(x => parseInt(x));

    const arr = a.filter((_, index) => locked[index]==0);
    arr.sort((a,b)=>b-a);

    let pos=0;
    const result = a.map((v, index)=> {
      if (locked[index]==1) return v;
      return arr[pos++];
    });

    console.log(result.join(" "));
  }
}

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    var time = Date.now();
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var t = +inputs[0];
    for (let i = 0; i < t; i++) {
        var n = +inputs[i * 3 + 1];
        var a = inputs[i * 3 + 2].split(' ').map(v => +v);
        var b = inputs[i * 3 + 3].split(' ').map(v => +v);
        var c = a.map((v, i) => b[i] ? -1e9 : v).sort((a, b) => b - a);
        var d = a.map((v, i) => b[i] ? v : c.shift());
        console.log(d.join(' '));
    }
})();
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(v)).reduce((p, v) => {
        p[v[0]] = v[1];
        return p;
    }, {});
};


You are given an array $$$a$$$ consisting of $$$500000$$$ integers (numbered from $$$1$$$ to $$$500000$$$). Initially all elements of $$$a$$$ are zero.You have to process two types of queries to this array:  $$$1$$$ $$$x$$$ $$$y$$$ — increase $$$a_x$$$ by $$$y$$$;  $$$2$$$ $$$x$$$ $$$y$$$ — compute $$$\sum\limits_{i \in R(x, y)} a_i$$$, where $$$R(x, y)$$$ is the set of all integers from $$$1$$$ to $$$500000$$$ which have remainder $$$y$$$ modulo $$$x$$$. Can you process all the queries?

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500000$$$) — the number of queries. Then $$$q$$$ lines follow, each describing a query. The $$$i$$$-th line contains three integers $$$t_i$$$, $$$x_i$$$ and $$$y_i$$$ ($$$1 \le t_i \le 2$$$). If $$$t_i = 1$$$, then it is a query of the first type, $$$1 \le x_i \le 500000$$$, and $$$-1000 \le y_i \le 1000$$$. If $$$t_i = 2$$$, then it it a query of the second type, $$$1 \le x_i \le 500000$$$, and $$$0 \le y_i < x_i$$$. It is guaranteed that there will be at least one query of type $$$2$$$.

For each query of type $$$2$$$ print one integer — the answer to it.

    var q = parseInt(readline(),10);
    var b = new Array(640000);
    for (var i = 0; i < b.length; ++i) b[i]=0;
    var a = new Array(500005);
    for (var i = 0; i < a.length; ++i) a[i]=0;
    var tmp, ans;
    for (var i = 0; i < q; ++i) {
        tmp=readline().split(' ');
        t=parseInt(tmp[0],10);
        x=parseInt(tmp[1],10);
        y=parseInt(tmp[2],10);
        if (t == 1) {
            a[x] += y;
            for (var j = 1; j <= 700; ++j) b[j*800+x%j] += y;
        }
        else if (t == 2) {
            if (x <= 700) print(b[x*800+y]);
            else {
                ans = 0;
                while (y <= 500000) {
                    ans += a[y];
                    y += x;
                }
                print(ans);
            }
        }
    }


In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.

The first line contains integer n (1 ≤ n ≤ 100) — the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≤ xi ≤ 104, 1 ≤ |di| ≤ 2·104) — records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.

If there are two camels, which spitted at each other, output YES. Otherwise, output NO.

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]);
	};
	return tokens;
}

function main() {
	var camelNum = parseInt(readline());
	var spitFrom = {};

	for (var i = 0; i < camelNum; ++i) {
		var info = tokenizeIntegers(readline());
		var camelPos = info[0], spitDistance = info[1];
		var target = camelPos + spitDistance;
		if (spitFrom[camelPos] == target) {
			print("YES");
			return;
		}
		spitFrom[target] = camelPos;
	}
	print("NO");
}

main();

'use strict'

let N = +readline()
let res = 'NO'
let lll

;(function () {
  let ss = []
  while (lll = readline()) {
    lll = lll.split(' ').map(v => parseInt(v))
    let vn = lll[0]
    let vs = lll[1]
    if (!ss[vn]) ss[vn] = []
    let vt = vn + vs
    if (ss[vt] && ~ss[vt].indexOf(vn)) return res = 'YES'
    ss[vn].push(vt)
  }
})()
print(res)

var n = parseInt(readline());
var verbluds = [];

for (var i = 0; i < n; i++) {
	var input = readline().split(' ').map(function(a){return parseFloat(a)});
	var position = input[0];
	var plevok_position = input[0] + input[1];
	verbluds[position] = plevok_position;
}

function is_odin_v_odnogo(arr) {
	for (var a in arr) {
		if (a == arr[arr[a]]) {
			return 'YES';
		}
	}
	return 'NO';
}

print(is_odin_v_odnogo(verbluds));

const readline = require('readline');

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

var dict = {}, n = -1;

rl.on('line', (input) => {
    if (n == -1)
        n = parseInt(input);
    else {
        let temp = input.split(' ').map(item=>parseInt(item));
        let pos = temp[0], spit = temp[1];
        dict[pos] = spit;
    }

  }).on('close', function() {
    let ans = "NO";

    for (var current in dict){
        let secondCamel = parseInt(dict[current]) + parseInt(current);
        if (secondCamel in dict && secondCamel + dict[secondCamel] == current) {
            ans = "YES";
            break;
        }
      }

      /*
      for (const [key, value] of Object.entries(dict)) {
        let secondCamel = dict[key] + value;
        if (secondCamel in dict && secondCamel + dict[secondCamel] == key) {
            ans = "YES";
            break;
        }
      }*/
      console.log(ans);
  });

  /*
    5
    2 -10
    3 10
    0 5
    5 -5
    10 1

  */

const readline = require('readline');

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

//var dict = {}, n = -1;
var myMap = new Map(), n = -1;

rl.on('line', (input) => {
    if (n == -1)
        n = parseInt(input);
    else {
        let temp = input.split(' ').map(item=>parseInt(item));

        let pos = temp[0], spit = temp[1];
       // dict[pos] = spit;

       myMap.set(pos, spit) ;
    }

  }).on('close', function() {
    let ans = "NO";
    /*
    for (var current in dict){
        let secondCamel = parseInt(dict[current]) + parseInt(current);
        if (secondCamel in dict && secondCamel + dict[secondCamel] == current) {
            ans = "YES";
            break;
        }
      }
      */
      /*
      for (const [key, value] of Object.entries(dict)) {
        let secondCamel = dict[key] + value;
        if (secondCamel in dict && secondCamel + dict[secondCamel] == key) {
            ans = "YES";
            break;
        }
      }*/

      for(let [key, value] of myMap){
         let secondCamel = key + value;
         if (myMap.has(secondCamel) && myMap.get(secondCamel) + secondCamel == key) {
             ans = "YES";
             break;
         }
      }
      console.log(ans);
  });

  /*
    5
    2 -10
    3 10
    0 5
    5 -5
    10 1

  */

const readline = require('readline');

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

var n = -1;
var location = [];
var spit = [];

rl.on('line', function (input) {
    // myArr = input.split(' ').map(item => {return parseInt(item);});
    if (n == -1)
        n = parseInt(input);
    else {

        if (location.length < n - 1) {
            //location.push(parseInt(input));
            var temp = input.split(' ').map(item=> {return parseInt(item);});
            location.push(temp[0]);
            spit.push(temp[1]);
        }
        else {

            var temp = input.split(' ').map(item=> {return parseInt(item);});
            location.push(temp[0]);
            spit.push(temp[1]);
        //****************************************** DO IT HERE*/
            var ans= "NO";
            for (let i = 0; i < n; i++) {
                var indexOfSecondCam = location.indexOf(location[i] + spit[i]);
                if (indexOfSecondCam != -1 && location[indexOfSecondCam] + spit[indexOfSecondCam]==location[i]) {
                    ans = "YES";
                    break;
                }

            }
            console.log(ans);

            rl.close();
            /*************************************** */
        }

    }

})

const readline = require('readline');

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

var dict = {}, n = -1;

rl.on('line', (input) => {
    if (n == -1)
        n = parseInt(input);
    else {
        let temp = input.split(' ');
        let pos = temp[0], spit = temp[1];
        dict[pos] = spit;
    }

  }).on('close', function() {
    let ans = "NO";

    for (var current in dict){
        let secondCamel = parseInt(dict[current]) + parseInt(current);
        if (secondCamel in dict && secondCamel + dict[secondCamel] == current) {
            ans = "YES";
            break;
        }
      }

      console.log(ans);
  });