Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 1\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^{9}$$$) — the current volume and Bob's desired volume, respectively.

For each test case, output a single integer — the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.

NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$.

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

// thats all what you have to write to get input from stdin, using readLine.

// Main code runs in main();

function main() {
    let testCases = readline();
    while(testCases --){
        var line2 = readline();
        let data = line2.split(' ').map(x => parseInt(x));
        checkSound(data);
    }
}

function checkSound([sound1, sound2]){
    let difference = Math.abs(sound1-sound2);
    let steps = 0;
    steps += parseInt(difference/5);
    if(difference%5 == 1 || difference%5 == 2){
        steps++;
    }
    else if(difference%5 == 3 || difference%5 == 4){
        steps += 2;
    }
    console.log(steps)
}

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, ''))

  const t = parseInt(arr.shift())

  const c = [0, 1, 1, 2, 2, 1]
  for(let i = 0; i < t; i++) {
    const arrT = arr[i].split(' ').map(a => parseInt(a))
    const a = arrT[0]
    const b = arrT[1]

    if(a == b) console.log(0)
    else {
      let diff = Math.abs(a - b)
      let count = Math.floor(diff / 5)
      diff = diff - count * 5

      count += c[diff]

      console.log(count)
    }
  }
})

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var a = one[0];
    var b = one[1];
    var diff = Math.abs(a - b);
    var count = Math.floor(diff / 5);
    diff %= 5;
    count += Math.floor(diff / 2);
    diff %= 2;
    count += diff;
    output[i] = count;
  }
  myout(myconv(output, 9));
}

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

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

  let [a, b] = d.split(' ').map(Number);
  let ans = 0;
  let target = Math.abs(a - b);
  const values = [5, 2, 1];
  let idx = 0;

  while (target > 0) {
    ans += Math.floor(target / values[idx]);
    target %= values[idx];
    idx++;
  }

  console.log(ans);
  c++;
});

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 n = nl.num();
  let ans = [];
  for(let i = 0; i < n; i++){
    let [a, b] = nl.nums();
    a = Math.abs(a - b);
    let c = Math.trunc(a/5);
    a %= 5;
    c += Math.trunc(a/2);
    a %= 2;
    c += a;
    ans.push(c);
  }
	console.log(ans.join('\n'));

};

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

var n = parseInt(readline());
var v = [0,1,1,2,2];

for(var i = 0;i<n;++i){
    var arr = readline().split(' ').map(v => parseInt(v));
    var d = Math.abs(arr[0] - arr[1]);
    print(Math.floor(d/5) + v[d%5]);
}

var t = readline();
var result = [];
for (var i = 0; i < t; i++) {
	var input = readline().split(" ");
	var diff = input[1] - input[0];
	var count = 0;
	var temp_count = 0;
	var button = [-5,-2,-1,1,2,5];
	if (diff < 0) {
		for (var j = 0; j < button.length && diff != 0; j++) {
			if (diff <= button[j]) {
				temp_count = Math.floor(diff/button[j]);
				count += temp_count;
				diff -= button[j]*temp_count;
			}
		}
	} else if (diff > 0) {
		for (var j = button.length - 1; j >= 0 && diff != 0; j--) {
			if (diff >= button[j]) {
				temp_count = Math.floor(diff/button[j]);
				count += temp_count;
				diff -= button[j]*temp_count;
			}
		}
	}
	result.push(count);
}
for (var i = 0; i < result.length; i++) {
	print(result[i]);
}

'use strict';

var t=parseInt(readline());

while(t--)
{
    var inp = readline().split(' ').map(Number);
    var a=inp[0];
    var b=inp[1];
    var cnt=Math.abs(a-b);

    var res=0;

    while(cnt)
    {
        if(cnt>=5){
            var tmp=parseInt(cnt/5);
            cnt-=(tmp*5);
            res+=tmp;
        }
        else if(cnt>=2){
            var tmp=parseInt(cnt/2);
            cnt-=(tmp*2);
            res+=tmp;
        }
        else {
            res+=cnt;
            cnt=0;
        }
    }

    print(res);
}

var go = function(a, b, steps, floor){
    var add = steps * floor;
    if(a<b) a = a + add;
    else a = a - add;

    if(a<0) return null;

    return countSteps(a,b);

}
var toward = function(a, b, steps){
    var diff = Math.abs(b-a);
    var div = diff/steps;
    var floor = Math.floor(div);
    if(floor>0){
        var h1 = go(a, b, steps, floor);
        var h2 = go(a, b, steps, floor+1);
        if(h2 === null) return floor + h1;
        else return floor + Math.min(h1,1 + h2);
    }
    else{
        h1 = go(a, b, steps, 1);
        if(h1 === null) return 0;
        else return 1 + go(a, b, steps, 1);
    }
}
var countSteps = function(a,b){
    if(a==b) return 0;
    var diff = Math.abs(b-a);
    if(diff > 6){
        return toward(a,b,5);
    }else if(diff === 1 || diff === 2 || diff === 5){
        return 1;
    }else{
        return 2;
    }
}

var n = parseInt(readline());
var i = 0;
while(i<n){
    var numbers = readline().split(" ");
    var a = parseInt(numbers[0]);
    var b = parseInt(numbers[1]);
    write(countSteps(a,b));

    i++;

    if(i!=n) write('\n');
}

var t = readline();
var result = [];
for (var i = 0; i < t; i++) {
	var input = readline().split(" ");
	var diff = input[1] - input[0];
	var count = 0;
	var button = [-5,-2,-1,1,2,5];
	if (diff < 0) {
		for (var j = 0; j < button.length && diff != 0; j++) {
			if (diff < button[j]) {
				count += Math.floor(diff/button[j]);
				diff -= button[j]*count;
			}
		}
	} else if (diff > 0) {
		for (var j = button.length - 1; j >= 0 && diff != 0; j--) {
			if (diff > button[j]) {
				count += Math.floor(diff/button[j]);
				diff -= button[j]*count;
			}
		}
	}
	result.push(count);
}
for (var i = 0; i < result.length; i++) {
	print(result[i]);
}

'use strict';

var t=Number(readline());

while(t--)
{
    var inp = readline().split(' ').map(Number);
    var a=inp[0];
    var b=inp[1];

    var cnt=Math.abs(a-b);

    var res=0;

    while(cnt)
    {
        if(cnt>=5){
            var tmp=cnt/5;
            cnt-=(tmp*5);
            res+=tmp;
        }
        else if(cnt>=2){
            var tmp=cnt/2;
            cnt-=(tmp*2);
            res+=tmp;
        }
        else {
            res+=cnt;
            cnt=0;
        }
    }

    print(res);
}

'use strict';

var t=parseInt(readline());

while(t--)
{
    var inp = readline().split(' ').map(parseInt);
    var a=inp[0];
    var b=inp[1];

    var cnt=parseInt (Math.abs(a-b));

    var res=0;

    while(cnt)
    {
        if(cnt>=5){
            var tmp=parseInt(cnt/5);
            cnt-=(tmp*5);
            res+=tmp;
        }
        else if(cnt>=2){
            var tmp=parseInt(cnt/2);
            cnt-=(tmp*2);
            res+=tmp;
        }
        else {
            res+=cnt;
            cnt=0;
        }
    }

    print(res);
}


You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.

NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (inputStd) => {
  inputString += inputStd;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let _ = readLine();
    let str = readLine();
    let stack = [];
    for (let i = 0; i < str.length; i++) {
      let char = str[i];
      if (stack[stack.length - 1] === "(" && char === ")") {
        stack.pop();
      } else {
        stack.push(char);
      }
    }
    console.log(stack.length / 2);
  }
}

//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var n = nextInt();
		var list = next();
		while(list.indexOf("()") != -1){
			list = list.replace("()","");
		}
		output[i] = list.length / 2;
	}
	myout(myconv(output,9));
}

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

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
});

process.stdin.on('end', () => {
  main(stdinInput);
});

function main(data) {
  data = data.split('\n');
  const testCases = data[0] * 2;
  let i = 1;
  while (i <= testCases) {
    let n = +data[i];
    let s = data[i + 1].trim();
    let count = 0;
    for (let j = 0; j < s.length; j += 1) {
      if (s[j] === '(') count += 1;
      else if (count && s[j] === ')') count -= 1;
    }
    console.log(count);
    i += 2;
  }
}

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() {
    function solve(sequence) {
        var moves = 0;
        var offset = 0;
        for (var i=0; i<sequence.length; i++) {
            if (sequence[i] === '(') {
                offset++;
            }
            else {
                if (offset >= 1) { offset--; }
                else { moves++; }
            }
        }
        return moves;
    }
    const testCases = parseInt(readline());
    for (var i=0; i<testCases; i++) {
        var length = parseInt(readline());
        var seq = readline();
        console.log(solve(seq));
    }
}

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 t = readLine() >> 0;

	while (t--) {
		let n = readLine();
		let s = readLine().split('');
		let pos = 0,
			move = 0;

		s.forEach(p => {
			if (p === '(') {
				pos++;
			} else {
				pos--;
				if (pos < 0) {
					pos = 0;
					move++;
				}
			}
		});

		console.log(move);
	}
}

'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++];
}
/**
4
2
)(
4
()()
8
())()()(
10
)))((((())

**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    let n = parseInt(readline());

    for(let r=0;r<n;r++) {
        solve();
    }

}

function solve() {
    let length = Number(readline());
    let s = readline().split("");

    const stack = [];
    let count = 0;

    for (let i = 0; i < s.length; i++) {
        const item = s[i];

        if (item === '(') {
            stack.push(item);
        } else {

            const prevItem = stack[stack.length - 1];
            if (item === ')' && prevItem === '(') {
                stack.pop();
            }
        }
    }

    console.log(stack.length);

}

const readline = require('readline');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        //do nothing?
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input) + '\n'
    }
    lineCount++
});

function compute(str) {
    for(var i=str.length-2;i>=0;i--){
        if(str[i]=='('&&str[i+1]==')'){
            // 删除他俩
            str = `${str.substring(0,i)}${str.substring(i+2, str.length)}`
        }
    }
    return str.length / 2
}

var n = readline();
var llen = [];
var inp = [];
for (var i  = 0; i<n;i++){
    llen[i]=readline();
    inp[i]=readline();
}
function repAll(aa) {
    var b  = true;
    var a = aa.length;
    while (b){
        aa = aa.replace(/\(\)/g,"");
        if (aa.length === a){

            b=false;
        }else{
            a = aa.length;
        }
    }
    return aa;
}
for (var i  = 0; i<n;i++) {
    var tmp = repAll(inp[i]);
    write((tmp.match(/\(/g) || []).length + "\n");

}

var x= parseInt(readline());

while(x--){
  var a=parseInt(readline());
  var seq=readline();

  var open=0,close=0;
  for(var i=0; i<seq.length; i++){
    if(seq[i]==='(')
      open++;
    if(seq[i]===')'){
      if(open>0)
        open--;
      else
        close++;
    }
  }
  print(close);
}

var testCase = Number(readline());
while(testCase--)
{
	readline();
	var str = readline();
	for( var i=1;i<=25;i++)
	{
		str=str.replace('()','');
	}
	print(Math.floor(str.length/2));
}

function solve() {
   var n = Number(read());
   var s = read();
   var min = 0;
   var sum = 0;
   for (var i = 0; i < n; i++) {
      sum += s[i] === '(' ? 1 : -1;
      if (sum < min) {
         min = sum;
      }
   }
   write(0 - min);
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}


A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules:  Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n);  each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;  each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;  as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.

The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 ≤ tij ≤ 1000), where tij is the time the j-th painter needs to work on the i-th picture.

Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.

print(function(m, n) {
    var i, j, ans=[], a=[];
    for(var i=0; i<m; ++i) a.push(rn());
    for(var i=0; i<m; ++i) ans[i]=0;
    for(var i=0; i<n; ++i) {
        for(var j=0; j<m; ++j) {
            if(j==0) ans[j]=ans[j]+a[j][i];
            else ans[j]=Math.max(ans[j-1], ans[j])+a[j][i];
        }
    }
    return ans.join(' ');
}.apply(0, rn()));
function rn() {
    return readline().split(' ').map(Number);
}

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 main() {
	var data = tokenizeIntegers(readline()),
		numPictures = data[0],
		numArtists = data[1],
		pictures = new Array(numPictures);
	for (var i = 0; i < numPictures; ++i) {
		data = tokenizeIntegers(readline());
		var suffixTime = 0;
		for (var j = 1; j < numArtists; ++j) {
			suffixTime += data[j];
		}
		pictures[i] = { index: i, artistTimes: data, suffixTime: suffixTime };
	}
	if (false) {
		pictures.sort(function (a, b) {
			return b.suffixTime - a.suffixTime;
		});
	}
	var finish = new Array(numPictures);
	finish[0] = new Array(numArtists);
	finish[0][0] = pictures[0].artistTimes[0];
	for (var p = 1; p < numPictures; ++p) {
		finish[p] = new Array(numArtists);
		finish[p][0] = finish[p-1][0] + pictures[p].artistTimes[0];
	}
	for (var a = 1; a < numArtists; ++a) {
		var available = finish[0][a] =
				finish[0][a-1] + pictures[0].artistTimes[a];
		for (var p = 1; p < numPictures; ++p) {
			var start = Math.max(available, finish[p][a-1]);
			available = finish[p][a] =
				start + pictures[p].artistTimes[a];
		}
	}
	var results = new Array(numPictures);
	for (var p = 0; p < numPictures; ++p) {
		results[pictures[p].index] = finish[p][numArtists-1];
	}
	print(results.join(" "));
}

main();

getInt = () => parseInt(readline());
getFlt = () => parseFloat(readline());
getArrInt = () => readline().split(' ').map(x => parseInt(x));
getArrFlt = () => readline().split(' ').map(x => parseFloat(x));
Int = (x) => Math.floor(x);

nums = getArrInt();
m = nums[0];
n = nums[1];

var t = new Array(m + 1);
for(i = 0; i <= m; i++) t[i] = new Array(n + 1);

for (var i = 1; i <= m; i++){
	tijs =
	readline()
	.split(' ')
	.map(x => parseInt(x))
	.forEach((el, j) => {
		t[i][j + 1] = el;
	});
}

dp = new Array( m + 1 ).fill(0);
for(var worker = 1; worker <= n; worker++){
	var getFree = 0;
	for(var pic = 1; pic <= m; pic++){
		getFree = Math.max(getFree, dp[pic]);
		dp[pic] = getFree + t[pic][worker];
		getFree = dp[pic];
	}
}

for(var pic = 1; pic <= m; pic++){
	write (dp[pic] + " ");
}

getInt = () => parseInt(readline());
getFlt = () => parseFloat(readline());
getArrInt = () => readline().split(' ').map(x => parseInt(x));
getArrFlt = () => readline().split(' ').map(x => parseFloat(x));
Int = (x) => Math.floor(x);

nums = getArrInt();
m = nums[0];
n = nums[1];

var t = new Array(m + 1);
for(i = 0; i <= m; i++) t[i] = new Array(n + 1);

for (var i = 1; i <= m; i++){
	tijs = readline().split(' ').map(x => parseInt(x));
	tijs.forEach((el, j) => {
		t[i][j + 1] = el;
	})
}

dp = new Array( m + 1 ).fill(0);
for(var worker = 1; worker <= n; worker++){
	var getFree = 0;
	for(var pic = 1; pic <= m; pic++){
		getFree = Math.max(getFree, dp[pic]);
		dp[pic] = getFree + t[pic][worker];
		getFree = dp[pic];
	}
}

for(var pic = 1; pic <= m; pic++){
	write (dp[pic] + " ");
}

getInt = () => parseInt(readline());
getFlt = () => parseFloat(readline());
getArrInt = () => readline().split(' ').map(x => parseInt(x));
getArrFlt = () => readline().split(' ').map(x => parseFloat(x));
Int = (x) => Math.floor(x);

nums = getArrInt();
m = nums[0];
n = nums[1];

var t = [];
for(i = 0; i <= m; i++) t[i] = [];

for (var i = 1; i <= m; i++){
	tijs = readline().split(' ').map(x => parseInt(x));
	tijs.forEach((el, j) => {
		t[i][j + 1] = el;
	})
}

dp = new Array( m + 1 ).fill(0);
for(var worker = 1; worker <= n; worker++){
	var getFree = 0;
	for(var pic = 1; pic <= m; pic++){
		getFree = Math.max(getFree, dp[pic]);
		dp[pic] = getFree + t[pic][worker];
		getFree = dp[pic];
	}
}

for(var pic = 1; pic <= m; pic++){
	write (dp[pic] + " ");
}

print(function(m, n){
	var i, j, ans = [], a = [];
	for(i=0; i<m; i++)
		a.push(rn());
	for(i=0; i<m; i++)
		ans[i] = 0;

	for(i=0; i<n; i++){
		for(j=0; j<m; j++){
			if(j==0){
				ans[j] = ans[j]+a[j][i];
			}else{
				ans[j] = Math.max( ans[j-1], ans[j] ) + a[j][i];
			}
		}
	}
	return ans.join(' ');
}.apply(0, rn()));
function rn() { return readline().split(' ').map(Number); }

var input = readline().split(' ');
var pictures = parseInt(input[0], 10);
var autors = parseInt(input[1], 10);
var info = [];

for (var i = 0; i < pictures; i++) {
    var input = readline().split(' ');
    info.push(input);
}

for(var i = 1; i < pictures; i++) {
    info[i][0] = parseInt(info[i][0], 10) + parseInt(info[i-1][0], 10);
}

for(var i = 1; i < autors; i++) {
    info[0][i] = parseInt(info[0][i], 10) + parseInt(info[0][i - 1], 10);
}

if (autors > 1) {
    for (var i = 1; i < pictures; i++) {
        for(var j = 1; j < autors; j++) {
            before = parseInt(info[i-1][j], 10);
            actual = parseInt(info[i][j-1], 10);
            info[i][j] = Math.max(before,actual) + parseInt(info[i][j]);
        }
    }
}

var result = [];
for (var i = 0; i < info.length; i++) {
    result.push(info[i].pop());
}
print(result.join(' '));

print(function(m, n) {
    var i, j, ans=[], a=[];
    for(var i=0; i<m; ++i) a.push(rn());

    for(var i=0; i<n; ++i) {
        for(var j=0; j<m; ++j) {
            if(j==0) ans[j]=ans[j]+a[j][i];
            else ans[j]=Math.max(ans[j-1], ans[j])+a[j][i];
        }
    }
    return ans.join(' ');
}.apply(0, rn()));
function rn() {
    return readline().split(' ').map(Number);
}

print(function(m, n) {
    var i, j, ans=[], a=[];
    for(var i=0; i<m; ++i) a.push(rn());
    for(var i=0; i<m; ++i) ans[i]=0;
    for(var i=0; i<n; ++i) {
        for(var j=0; j<m; ++j) {
            if(j==0) ans[j]=a[j][i];
            else ans[j]=Math.max(ans[j-1], ans[j])+a[j][i];
        }
    }
    return ans.join(' ');
}.apply(0, rn()));
function rn() {
    return readline().split(' ').map(Number);
}


Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.

Print a single integer — the minimum number of seconds needed to destroy the entire line.

NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

var input = readline().split(' ').map(Number), n = input[0];
var a = readline().split(' ').map(Number);
var s = [];
for (var i = 0; i < n; i++) {
    s[i] = [];
    for (var j = 0; j < n; j++) s[i][j] = 0;
    s[i][i] = 1;
}

for (var i = n - 1; i >= 0; i--) {
    for (var j = n - 1; j > i; j--) {
        var minV = Infinity;
        minV = Math.min(minV, s[i+1][j] + 1);
        for (var k = i+1; k <= j; k++) {
            if (a[i] == a[k])
                minV = Math.min(minV, ((k-1 >= 0) ? (Math.max(s[i+1][k-1], 1)) : 0) + ((k+1 < n) ? s[k+1][j] : 0));
        }

        if (a[i] == a[i+1] && i+2 < n) minV = Math.min(minV, s[i+2][j] + 1);
        s[i][j] = minV;
    }
}

write(s[0][n-1]);


A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days.Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i. e. in evening). Initially the account's balance is zero rubles.

The first line contains three integers n, p and m (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109, 1 ≤ m ≤ 109, n ≤ m) — the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check. The i-th of the following n lines contains two integers di and ti (1 ≤ di ≤ m, 1 ≤ ti ≤ 109) — the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i. e. di > di - 1 for all i from 2 to n.

Print the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment.

NoteIn the first example the balance will change as following (remember, initially the balance is zero):  in the first day 6 rubles will be charged, the balance in the evening will be equal to  - 6;  in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1;  in the third day 6 rubles will be charged, the balance in the evening will be equal to  - 5;  in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9;  in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3;  in the sixth day 6 rubles will be charged, the balance in the evening will be equal to  - 3;  in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0. Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day.

function parseNumber(x) {
    return parseInt(x);
}

var numbers = readline().split(" ").map(parseNumber);
var N = numbers[0], P = numbers[1], M = numbers[2];
var balance = 0, numOfDays = 0, payments = [];
var lastPaidDay = 0;

for(var i = 0; i < N; i++) {
    var pay = readline().split(" ").map(parseNumber);
	var day = pay[0];
	var value = pay[1];

	var positiveDays = Math.floor(balance / P);
	positiveDays = positiveDays > 0 ?  positiveDays : 0;

	var countedDays = day - lastPaidDay - 1;
	var negDays = countedDays - positiveDays;
	balance -= P*countedDays;

	if(negDays > 0) {
		numOfDays+=negDays;
	}

	balance = balance + value - P;
	if(balance < 0) {
		numOfDays++;
	}

	lastPaidDay = day;
}

var positiveDays = Math.floor(balance / P);
positiveDays = positiveDays > 0 ?  positiveDays : 0;
var countedDays = M - lastPaidDay;
var negDays = countedDays - positiveDays
balance -= P*countedDays;

if(negDays > 0) {
	numOfDays+=negDays;
}

write(numOfDays);

function min(a, b) {
  if (a < b) {
    return a;
  } else {
    return b;
  }
}

var line_0 = readline().split(' ');

var n = parseInt(line_0[0]);
var p = parseInt(line_0[1]);
var m = parseInt(line_0[2]);

var answer = 0;

var balance = 0;
var day = 1;
for (var i = 1; i <= n; ++i) {
    var line = readline().split(' ');

    var d = parseInt(line[0]);
    var t = parseInt(line[1]);

    //print(d, day, (d - day) * p);

    balance -= (d - day) * p;
    if (balance < 0) {
        var tmp = -balance;
        var add = min(d - day, Math.ceil(tmp / p));
        answer += add;
        //print("!!", add, "!!", balance, Math.ceil(tmp / p), d - day);
    }
    balance += t;
    day = d;
}
//print(answer);

balance -= (m+1 - day) * p;
if (balance < 0) {
    var tmp = -balance;
    //print("@@", m - day);
    answer += min(m+1 - day, Math.ceil(tmp / p));
}
print(answer);

function parseNumber(x) {
    return parseInt(x);
}

var numbers = readline().split(" ").map(parseNumber);
var N = numbers[0], P = numbers[1], M = numbers[2];
var balance = 0, numOfDays = 0, payments = [];
var lastPaidDay = 0;

for(var i = 0; i < N; i++) {
    var pay = readline().split(" ").map(parseNumber);
	var day = pay[0];
	var value = pay[1];

	var positiveDays = Math.floor(balance / P);

	var countedDays = day - lastPaidDay - 1;
	var negDays = countedDays - positiveDays;
	balance -= P*countedDays;

	if(negDays > 0) {
		numOfDays+=negDays;
	}

	balance = balance + value - P;
	if(balance < 0) {
		numOfDays++;
	}

	lastPaidDay = day;
}

var positiveDays = Math.floor(balance / P);
var countedDays = M - lastPaidDay;
var negDays = countedDays - positiveDays
balance -= P*countedDays;

if(negDays > 0) {
	numOfDays+=negDays;
}

write(numOfDays);


All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $$$n\cdot m$$$ different seals, denoted by distinct numbers. All of them were written in an $$$n\times m$$$ table.The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.

The first line of the input contains the only integer $$$t$$$ ($$$1\leq t\leq 100\,000$$$) denoting the number of test cases. Their descriptions follow. The first line of each test case description consists of two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $$$1$$$ to $$$n\cdot m$$$. The following $$$n$$$ lines contain $$$m$$$ space separated integers each, denoting elements of an arbitrary row in the table left to right. The following $$$m$$$ lines contain $$$n$$$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom. Sum of $$$nm$$$ over all test cases does not exceed $$$250\,000$$$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $$$1$$$ to $$$nm$$$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.

For each test case, output $$$n$$$ lines with $$$m$$$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.

NoteConsider the first test case. The matrix is $$$2 \times 3$$$. You are given the rows and columns in arbitrary order.One of the rows is $$$[6, 5, 4]$$$. One of the rows is $$$[1, 2, 3]$$$.One of the columns is $$$[1, 6]$$$. One of the columns is $$$[2, 5]$$$. One of the columns is $$$[3, 4]$$$.You are to reconstruct the matrix. The answer is given in the output.

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));
const sub = (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 pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [rowLen, colLen] = readLine().split(" ").map(Number);
    const [rowMap, colMap] = [new Map(), new Map()];
    const result = [...Array(rowLen).fill(0)].map((_) => Array(colLen).fill(0));
    for (let i = 0; i < rowLen; i++) {
      readLine()
        .split(" ")
        .map((n, index) => {
          n = parseInt(n);
          colMap.set(n, index);
        });
    }
    for (let i = 0; i < colLen; i++) {
      readLine()
        .split(" ")
        .map((n, index) => {
          n = parseInt(n);
          rowMap.set(n, index);
          const col = colMap.get(n);
          result[index][col] = n;
        });
    }

    for (let i = 0; i < rowLen; i++) {
      console.log(result[i].join(" "));
    }
  }
}

//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 t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		var list = new Array(N);
		for(var j = 0; j < N; j++){
			list[j] = new Array(M);
		}
		var check = new Array(N);
		var check2 = new Array(M);
		var map = {};
		for(var j = 0; j < N; j++){
			check[j] = nextIntArray();
			for(var k = 0; k < M; k++){
				map[check[j][k]] = k;
			}
		}

		for(var j = 0; j < M; j++){
			tmp = nextIntArray();
			var L = map[tmp[0]];
			for(var k = 0; k < N; k++){
				list[k][L] = tmp[k];
			}
		}
		for(var j = 0; j < N; j++){
			output.push(myconv(list[j], 8));
		}

	}
	myout(myconv(output, 9));
}
function lcm(m, n) {return (m / gcd(m, n)) * n;}	function gcd(m, n) {return n != 0 ? gcd(n, m % n) : m;}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;o<t;++o){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const o=n(r(747));let s="",i=[],u=0,l="";const a="local"===process.argv[2],p=t=>{if(a){if(i=o.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),o.default.writeFileSync("output.txt",l),console.log(l),o.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{s+=t})),process.stdin.on("end",(e=>{i=s.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function f(){return i[u++]}function h(){return f().split(" ").map((t=>parseFloat(t)))}function c(){return f().split("")}e.default={runMain:p,runEachTest:t=>{p((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:f,nextNumbers:h,nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const o=n(r(312));o.default.runEachTest((function(){let[t,e]=o.default.nextNumbers(),r=o.default.nextNumbersMatrix(t),n=r.transpose(),s=[...n[0]].sortAsc().join(""),i=o.default.nextNumbersMatrix(e),u=i.deepCopy().map((t=>t.sortAsc().join(""))),l=i[u.findIndex((t=>t==s))],a=n[0].map((t=>l.indexOf(t))),p=Array.numbersMatrix(t,e),f=0;for(let t of a){for(let n=0;n<e;++n)p[t][n]=r[f][n];f++}o.default.puts(p.toString())}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, m] = io.nextNumbers()
//   let a = io.nextNumbersMatrix(n)
//
//   let cols = a.transpose()
//
//   let c = [...cols[0]].sortAsc().join("")
//   let b = io.nextNumbersMatrix(m)
//   let bb = b.deepCopy().map((x) => x.sortAsc().join(""))
//
//   let f = b[bb.findIndex((x) => x == c)]
//
//   let indices = cols[0].map((x) => f.indexOf(x))
//
//   let h = Array.numbersMatrix(n, m)
//   let k = 0
//
//   for (let i of indices) {
//     for (let j = 0; j < m; ++j) {
//       h[i][j] = a[k][j]
//     }
//     k++
//   }
//
//   io.puts(h.toString())
// }
//
// io.runEachTest(main)
// // io.runMain(main)

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

    B();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let cols = new Array(n);
        for(let i = 0; i < n; i++){
            cols[i] = readline().split(' ');
        }

        let rows = new Array(m);
        for(let i = 0; i < m; i++){
            rows[i] = readline().split(' ');
        }

        let map = new Array(10);
        for(let i = 0; i < n; i++){
            for(let j = 0; j < m; j++){
                map[pi(cols[i][j])] = new Array(2);
                map[pi(cols[i][j])][1] = j;
            }
        }

        for(let i = 0; i < m; i++){
            for(let j = 0; j < n; j++){
                map[pi(rows[i][j])][0] = j;
            }
        }

        let res = new Array(n);
        for(let i = 0; i < n; i++){
            res[i] = new Array(m);
        }

        for(let i = 0; i < n; i++){
            for(let j = 0; j < m; j++){
                let r = map[pi(cols[i][j])][0];
                let c = map[pi(cols[i][j])][1];
                res[r][c] = cols[i][j];
            }
        }

        for(let i = 0; i < n; i++){
            console.log(res[i].join(' '));
        }
    }
}


Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\{1, 2, 2, 3\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

The first line of input contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \le b_i \le 10^6$$$), describing the list of the player B.

Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.

NoteIn the first example, the game could have gone as follows:   A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A takes his $$$1$$$.  B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing:  A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A removes $$$1$$$ from B's list.  B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$.

var n = +readline();
var a = readline().split(' ').map(Number).sort((x,y)=>y-x),b = readline().split(' ').map(Number).sort((x,y)=>y-x), turna = true, i = 0,j =0;
var suma = 0, sumb = 0;
while (i < n && j < n){
    if (turna){
        turna = false;
        if (a[i] >= b[j]){
            suma += a[i];
            i++;
        } else if (a[i] < b[j]){
            j++;
        }
    } else {
        turna = true;
        if (b[j] >= a[i]){
            sumb += b[j];
            j++;
        } else if (b[j] < a[i]){
            i++;
        }
    }
}
if (i !== n){
    if (!turna) i++;
    while (i < n){
        suma += a[i];
        i+=2;
    }
} else if (j !== n) {
    if (turna) j++;
    while (j < n){
        sumb += b[j];
        j+= 2;
    }
}
print(suma - sumb);

// Gambling - https://codeforces.com/problemset/problem/1038/C

const main = async () => {
    let listLen = 0;
    const listA = [];
    const listB = [];

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

    for await (const line of rl) {
      if (!listLen) {
        listLen = Number(line);
      } else {
        if (listA.length < listLen) {
            sortList(line.split(' ')).map((item)=> listA.push(Number(item)));
        } else {
            rl.close();
            sortList(line.split(' ')).map((item)=> listB.push(Number(item)));
        }
      }
    }

    runGame(listLen, listA, listB);
  };

  const sortList = (list) => list.sort((a, b) => a - b)

  const runGame = (listLen, listA, listB) => {

    let scoreA = 0;
    let scoreB = 0;

    for (let i = 0; i <= listLen * 2; i++) {
        // console.log({listA, scoreA, '':'', scoreB, listB})
        if (i % 2 === 0) {
            if (!listB.length || listA[listA.length - 1] > listB[listB.length - 1]) {
                scoreA += listA[listA.length - 1] || 0;
                listA.pop()
            } else {
                listB.pop()
            }
        } else {
            if (!listA.length || listB[listB.length - 1] > listA[listA.length - 1]) {
                scoreB += listB[listB.length - 1] || 0;
                listB.pop()
            } else {
                listA.pop()
            }
        }

    }

    console.log(scoreA - scoreB);
  };

  main();

var n = +readline();
var a = readline().split(' ').map(Number).sort((x,y)=>y-x),b = readline().split(' ').map(Number).sort((x,y)=>y-x), turna = true, i = 0,j =0;
var suma = 0, sumb = 0;
while (i < n && j < n){
    if (turna){
        turna = false;
        if (a[i] > b[j]){
            suma += a[i];
            i++;
        } else if (a[i] < b[j]){
            j++;
        } else {
            i++;
            j++;
        }
    } else {
        turna = true;
        if (b[j] > a[i]){
            sumb += b[j];
            j++;
        } else if (b[j] < a[i]){
            i++;
        } else {
            i++;j++;
        }
    }
}
if (i !== n){
    while (i < n){
        suma += a[i];
        i+=2;
    }
} else if (j !== n) {
    while (j < n){
        sumb += b[j];
        j+= 2;
    }
}
print(suma - sumb);

var n = +readline();
var a = readline().split(' ').map(Number).sort((x,y)=>y-x),b = readline().split(' ').map(Number).sort((x,y)=>y-x), turna = true, i = 0,j =0;
var suma = 0, sumb = 0;
while (i < n && j < n){
    if (turna){
        turna = false;
        if (a[i] >= b[j]){
            suma += a[i];
            i++;
        } else if (a[i] < b[j]){
            j++;
        }
    } else {
        turna = true;
        if (b[j] >= a[i]){
            sumb += b[j];
            j++;
        } else if (b[j] < a[i]){
            i++;
        }
    }
}
if (i !== n){
    while (i < n){
        suma += a[i];
        i+=2;
    }
} else if (j !== n) {
    while (j < n){
        sumb += b[j];
        j+= 2;
    }
}
print(suma - sumb);


Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a1, a2, ..., an (0 ≤ ai ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number ai.

In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.

NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.

function ProblemSolver() {
    this.HAS_TEST_CASES = false ;
    this.INPUT_FILE_NAME = "sample.in" ;
    this.OUTPUT_FILE_NAME = "sample.out" ;
    this.DO_OUTPUT_TO_FILE = false ;
    this.CLEAR_ARRAY_PER_CASE = false ;

    this.solveCase = function() {
        var res , i , j , fl , cn , a , b , c , d , e ;
        res = false ;
        a = 0 ;
        b = 0 ;
        for( i = 0 ; i < this.n ; i++ ) {
            c = this.arr[ i ] ;
            d = 0 ;
            if( b == 0 ) {
                while( true ) {
                    if( c == a ) {
                        break ;
                    }
                    d++ ;
                    c = ( c + 1 ) % this.n ;
                }
            }
            else {
                while( true ) {
                    if( c == a ) {
                        break ;
                    }
                    d++ ;
                    c = ( c - 1 + this.n ) % this.n ;
                }
            }
            this.brr[ i ] = d ;
            b = ! b ;
            a++ ;
        }
        a = 1 ;
        for( i = 1 ; i < this.n ; i++ ) {
            if( this.brr[ i ] != this.brr[ i - 1 ] ) {
                a = 0 ;
                break ;
            }
        }
        if( a == 1 ) {
            res = true ;
        }
        else {
            a = 0 ;
            b = 0 ;
            for( j = 0 ; j < 10000 ; j++ ) {
                e = 1 ;
                for( i = 0 ; i < this.n ; i++ ) {
                    c = this.arr[ i ] ;
                    if( b == 0 ) {
                        this.arr[ i ] = ( this.arr[ i ] + 1 ) % this.n ;
                    }
                    else {
                        this.arr[ i ] = ( this.arr[ i ] - 1 + this.n ) % this.n ;
                    }
                    if( this.arr[ i ] != i ) {
                        e = 0 ;
                    }
                    b = ! b ;
                    a++ ;
                }
                if( e == 1 ) {
                    res = true ;
                    break ;
                }
            }
        }
        if( res == true ) {
            print( 'Yes' ) ;
        }
        else {
            print( 'No' ) ;
        }
    } ;

    this.init = function() {
        this.lim1 = 100010 ;
        this.lim2 = 110 ;
        this.cc = 1 ;
        this.ind = 1 ;
        this.n = 0 ;
        this.cn = 0 ;
        this.declareAndFillArrays() ;
    } ;

    this.getInput = function( irObj ) {
        var hasMoreInput , i ;
        hasMoreInput = true ;
        try {
        	this.n = irObj.nextInt() ;
            this.arr = [] ;
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr.push( irObj.nextInt() ) ;
            }
        }
        catch( ex ) {
            hasMoreInput = false ;
        }
        return hasMoreInput ;
    } ;

    this.clearArraysPerCase = function() {
        var i ;
        this.arr = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
    } ;

    this.clearPerCase = function() {
        this.cn = 0 ;
        this.cc++ ;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    } ;

    this.declareAndFillArrays = function() {
        var i , j ;
        this.srr = new Array() ;
        this.vis = new Array() ;
        this.arr = new Array() ;
        this.brr = new Array() ;
        this.memo = new Array() ;
        this.done = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( '' ) ;
            this.vis.push( 0 ) ;
            this.arr.push( 0 ) ;
            this.brr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() ) ;
            this.done.push( new Array() ) ;
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 ) ;
                this.done[ i ].push( 0 ) ;
            }
        }
    } ;

    this.init() ;
}

function InputReader() {
    var self = this ;
    this.allLines = new Array() ;
    this.currrentLineNumber = 0 ;
    this.currrentCharacterIndex = 0 ;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine ;
        while( true ) {
            try {
                singleLine = readline() ;
                if( singleLine == null ) {
                    break ;
                }
            }
            catch( ex ) {
                break ;
            }
            this.allLines.push( singleLine ) ;
        }
    } ;

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    } ;

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    } ;

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    } ;

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    } ;

    this.parseRawData = function( data ) {
        var len , i , currentString ;
        len = data.length ;
        currentString = '' ;
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString ) ;
                currentString = '' ;
            }
            else {
                currentString += data[ i ] ;
            }
        }
        if( currentString != '' ) {
            this.allLines.push( currentString ) ;
        }
    } ;

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData ;
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            inputFilePath = currentDirectory + '\\' + inputFileName ;
        }
        else {
            //on linux
            inputFilePath = currentDirectory + '/' + inputFileName ;
        }
        rawData = fsObj.readFileSync( inputFilePath , "utf8" ) ;
        this.parseRawData( rawData ) ;
    } ;

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx ;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            res = '' ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++ ;
            this.currrentCharacterIndex = 0 ;
            return res ;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( 'No more tokens available!' ) ;
            }
            startIdx = -1 ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i ;
                    break ;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
                continue ;
            }
            res = '' ;
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i ;
                    break ;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
                }
            }
            this.currrentCharacterIndex = endIdx ;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            return res ;
        }
    } ;

    this.nextInt = function() {
        return parseInt( this.next( 1 ) ) ;
    } ;

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) ) ;
    } ;

    this.nextString = function() {
        return this.next( 1 ) ;
    } ;

    this.nextLine = function() {
        return this.next( 0 ) ;
    } ;
}

function FileOutputHandler() {
    this.resultantStringArray = new Array() ;

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString ) ;
    } ;

    this.clearPercase = function() {
        this.resultantStringArray = new Array() ;
    } ;

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath ;
        res = '' ;
        sz = this.resultantStringArray.length ;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += '\n' ;
            }
            res += this.resultantStringArray[ i ] ;
        }
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            outputFilePath = currentDirectory + '\\' + outputFileName ;
        }
        else {
            //on linux
            outputFilePath = currentDirectory + '/' + outputFileName ;
        }
        fsObj.writeFileSync( outputFilePath , res ) ;
        this.clearPercase() ;
    } ;
}

function CodeExecutioner() {
    this.irObj = new InputReader() ;
    this.psObj = new ProblemSolver() ;
    this.fohObj = new FileOutputHandler() ;

    this.runCases = function() {
		var testCases , hasMoreTestCases , i ;
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt() ;
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase() ;
                this.psObj.getInput( this.irObj ) ;
                this.psObj.solveCase() ;
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase() ;
                hasMoreTestCases = this.psObj.getInput( this.irObj ) ;
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase() ;
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME ) ;
        }
    } ;

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && ( __dirname.indexOf( 'D:') != -1 || __dirname.indexOf( '/media/') != -1 ) ) {
                    environmentType = 'local-node-js' ;
                }
                else {
                    environmentType = 'server-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    } ;

    this.configureStreamsAndReadInput = function() {
        var localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj ;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments ) ;
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME ) ;
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino() ;
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
    } ;

    this.configureStreamsAndReadInput() ;
}

new CodeExecutioner() ;

function ProblemSolver() {
    this.HAS_TEST_CASES = false ;
    this.INPUT_FILE_NAME = "sample.in" ;
    this.OUTPUT_FILE_NAME = "sample.out" ;
    this.DO_OUTPUT_TO_FILE = false ;
    this.CLEAR_ARRAY_PER_CASE = false ;

    this.solveCase = function() {
        var res , i , j , fl , cn , a , b , c , d , e ;
        res = false ;
        a = 0 ;
        b = 0 ;
        for( i = 0 ; i < this.n ; i++ ) {
            c = this.arr[ i ] ;
            d = 0 ;
            if( b == 0 ) {
                while( true ) {
                    if( c == a ) {
                        break ;
                    }
                    d++ ;
                    c = ( c + 1 ) % this.n ;
                }
            }
            else {
                while( true ) {
                    if( c == a ) {
                        break ;
                    }
                    d++ ;
                    c = ( c - 1 + this.n ) % this.n ;
                }
            }
            this.brr[ i ] = d ;
            b = ! b ;
            a++ ;
        }
        a = 1 ;
        for( i = 1 ; i < this.n ; i++ ) {
            if( this.brr[ i ] != this.brr[ i - 1 ] ) {
                a = 0 ;
                break ;
            }
        }
        if( a == 1 ) {
            res = true ;
        }
        else {
        }
        if( res == true ) {
            print( 'Yes' ) ;
        }
        else {
            print( 'No' ) ;
        }
    } ;

    this.init = function() {
        this.lim1 = 100010 ;
        this.lim2 = 110 ;
        this.cc = 1 ;
        this.ind = 1 ;
        this.n = 0 ;
        this.cn = 0 ;
        this.declareAndFillArrays() ;
    } ;

    this.getInput = function( irObj ) {
        var hasMoreInput , i ;
        hasMoreInput = true ;
        try {
        	this.n = irObj.nextInt() ;
            this.arr = [] ;
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr.push( irObj.nextInt() ) ;
            }
        }
        catch( ex ) {
            hasMoreInput = false ;
        }
        return hasMoreInput ;
    } ;

    this.clearArraysPerCase = function() {
        var i ;
        this.arr = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
    } ;

    this.clearPerCase = function() {
        this.cn = 0 ;
        this.cc++ ;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    } ;

    this.declareAndFillArrays = function() {
        var i , j ;
        this.srr = new Array() ;
        this.vis = new Array() ;
        this.arr = new Array() ;
        this.brr = new Array() ;
        this.memo = new Array() ;
        this.done = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( '' ) ;
            this.vis.push( 0 ) ;
            this.arr.push( 0 ) ;
            this.brr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() ) ;
            this.done.push( new Array() ) ;
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 ) ;
                this.done[ i ].push( 0 ) ;
            }
        }
    } ;

    this.init() ;
}

function InputReader() {
    var self = this ;
    this.allLines = new Array() ;
    this.currrentLineNumber = 0 ;
    this.currrentCharacterIndex = 0 ;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine ;
        while( true ) {
            try {
                singleLine = readline() ;
                if( singleLine == null ) {
                    break ;
                }
            }
            catch( ex ) {
                break ;
            }
            this.allLines.push( singleLine ) ;
        }
    } ;

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    } ;

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    } ;

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    } ;

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    } ;

    this.parseRawData = function( data ) {
        var len , i , currentString ;
        len = data.length ;
        currentString = '' ;
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString ) ;
                currentString = '' ;
            }
            else {
                currentString += data[ i ] ;
            }
        }
        if( currentString != '' ) {
            this.allLines.push( currentString ) ;
        }
    } ;

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData ;
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            inputFilePath = currentDirectory + '\\' + inputFileName ;
        }
        else {
            //on linux
            inputFilePath = currentDirectory + '/' + inputFileName ;
        }
        rawData = fsObj.readFileSync( inputFilePath , "utf8" ) ;
        this.parseRawData( rawData ) ;
    } ;

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx ;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            res = '' ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++ ;
            this.currrentCharacterIndex = 0 ;
            return res ;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( 'No more tokens available!' ) ;
            }
            startIdx = -1 ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i ;
                    break ;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
                continue ;
            }
            res = '' ;
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i ;
                    break ;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
                }
            }
            this.currrentCharacterIndex = endIdx ;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            return res ;
        }
    } ;

    this.nextInt = function() {
        return parseInt( this.next( 1 ) ) ;
    } ;

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) ) ;
    } ;

    this.nextString = function() {
        return this.next( 1 ) ;
    } ;

    this.nextLine = function() {
        return this.next( 0 ) ;
    } ;
}

function FileOutputHandler() {
    this.resultantStringArray = new Array() ;

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString ) ;
    } ;

    this.clearPercase = function() {
        this.resultantStringArray = new Array() ;
    } ;

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath ;
        res = '' ;
        sz = this.resultantStringArray.length ;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += '\n' ;
            }
            res += this.resultantStringArray[ i ] ;
        }
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            outputFilePath = currentDirectory + '\\' + outputFileName ;
        }
        else {
            //on linux
            outputFilePath = currentDirectory + '/' + outputFileName ;
        }
        fsObj.writeFileSync( outputFilePath , res ) ;
        this.clearPercase() ;
    } ;
}

function CodeExecutioner() {
    this.irObj = new InputReader() ;
    this.psObj = new ProblemSolver() ;
    this.fohObj = new FileOutputHandler() ;

    this.runCases = function() {
		var testCases , hasMoreTestCases , i ;
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt() ;
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase() ;
                this.psObj.getInput( this.irObj ) ;
                this.psObj.solveCase() ;
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase() ;
                hasMoreTestCases = this.psObj.getInput( this.irObj ) ;
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase() ;
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME ) ;
        }
    } ;

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && ( __dirname.indexOf( 'D:') != -1 || __dirname.indexOf( '/media/') != -1 ) ) {
                    environmentType = 'local-node-js' ;
                }
                else {
                    environmentType = 'server-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    } ;

    this.configureStreamsAndReadInput = function() {
        var localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj ;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments ) ;
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME ) ;
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino() ;
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
    } ;

    this.configureStreamsAndReadInput() ;
}

new CodeExecutioner() ;

var n = parseInt(readline());
var actives = readline().split(' ').map(function(a){
	return parseInt(a);
});

function is_finished() {
	for (var i = 0; i < n; i++) {
		if (actives[i] != i) {
			return false
		}
	}
	return true;
}

function action() {
	for (var i = 0; i < n; i++) {
		if (i % 2) {
			actives[i]--;
		} else {
			actives[i]++;
		}
		if (actives[i] < 0) {
			actives[i] = n-1;
		}
		actives[i] = actives[i] % n;
	}
}

var finished = false;

for (var i = 0; i < n; i++) {
	if (is_finished()) {
		print('Yes');
		finished=true;
		break;
	}
	action();
}
if (!finished) {
	print('No');
}

var n = Number(readline());

var gears = readline().split(' ').map(Number);
var trueGears = [],
    res = 'NO';

Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
};

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

for (var j = 0; j < n; j++) {
    for (i = 0; i < gears.length; i++) {
        if ( i % 2 == 0 ) {
            gears[i]++;
        } else {
            gears[i]--;
        }

        gears[i] = gears[i].mod(n);
    }

    if ( arrayEqual(trueGears, gears) ) {
        res = 'YES';
        break;
    }
}

print( res );

function arrayEqual(arr1, arr2) {
    if ( arr1.length !== arr2.length ) {
        return false;
    }

    for (var i = 0; i < arr2.length; i++) {
        if ( arr2[i] !== arr1[i] ) {
            return false;
        }
    }

    return true;
};


Zibi is a competitive programming coach. There are $$$n$$$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the $$$i$$$-th competitor will always have score $$$x_i$$$ when he codes the first task and $$$y_i$$$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are $$$m$$$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 300\,000$$$, $$$0 \le m \le 300\,000$$$) — the number of participants and the number of pairs of people who will not write a contest together. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$) — the scores which will the $$$i$$$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $$$x_i$$$ and $$$y_i$$$ same. Each of the next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.

Output $$$n$$$ integers — the sum of scores for all participants in the same order as they appear in the input.

NoteIn the first example, there will be only one team consisting of persons $$$1$$$ and $$$3$$$. The optimal strategy for them is to assign the first task to the $$$3$$$-rd person and the second task to the $$$1$$$-st person, this will lead to score equal to $$$1 + 2 = 3$$$.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case...

        'use strict';

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

        const ans = new Array(n);

        const x = new Array(n);
        const y = new Array(n);
        const diff = new Array(n);
        for (let i = 0; i < n; i++) {
            const line = readline().split(' ').map(Number);
            x[i] = line[0];
            y[i] = line[1];

            diff[i] = [y[i] - x[i], i];
        }

        diff.sort(function(lhs, rhs) {return (lhs[0] !== rhs[0]) ? lhs[0] - rhs[0] : lhs[1] - rhs[1]});

        const prefsum = new Array(n + 1);
        prefsum[0] = 0;
        for (let i = 0; i < n; i++) {
            const id = diff[i][1];
            prefsum[i + 1] = prefsum[i] + y[id];
        }

        const suffsum = new Array(n + 1);
        suffsum[n] = 0;
        for (let i = n - 1; i >= 0; i--) {
            const id = diff[i][1];
            suffsum[i] = suffsum[i + 1] + x[id];
        }

        for (let i = 0; i < n; i++) {
            const id = diff[i][1];
            ans[id] = prefsum[i] + x[id] * i + suffsum[i + 1] + y[id] * (n - i - 1);
        }

        for (let i = 0; i < m; i++) {
            const line = readline().split(' ').map(Number);
            const v = line[0] - 1;
            const u = line[1] - 1;
            const score = Math.min(x[v] + y[u], x[u] + y[v]);
            ans[v] -= score;
            ans[u] -= score;
        }

        print(ans.join(' '));

function split(v) {
   var pos = v.indexOf(' ');
   return [+v.substr(0, pos), +v.substr(pos + 1)]
}

var fl = readline().split(' ').map(v=>+v);
var persCnt = fl[0];
var pairsCnt = fl[1];

var persons = [], scores = [], all1 = 0, all2 = 0;
for(var i = 0; i < persCnt; i++) {
    var rl = split(readline());
    persons.push([i, rl[0], rl[1], rl[1] - rl[0], 0]);

    all2 += rl[1]
}

for(i = 0; i < pairsCnt; i++) {
    var pair = split(readline());
    var person1 = persons[pair[0] - 1];
    var person2 = persons[pair[1] - 1];
    var sum = person1[3] > person2[3]
        ? person1[1] + person2[2]
        : person1[2] + person2[1]

    person1[4] -= sum
    person2[4] -= sum
}

scores.length = persCnt;

persons.sort((a, b) => a[3] > b[3] ? -1 : 1);
for(var i = 0; i < persCnt; i++) {
    var person = persons[i]
    all2-=person[2]
    scores[person[0]] =
        person[1] * (persCnt - i - 1) +
        person[2] * i
        + all2 + all1
        + person[4]

    all1+=person[1]
}

print(scores.join(' '));