The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.

The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.

Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.

6
Jack captain
Alice woman
Charlie man
Teddy rat
Bob child
Julia woman

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1, -1).forEach(line => {
    let [n, s] = line.split(' ')
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else if (s == 'child') s = 1
    else if (s == 'man') s = 2
    else s = 3
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1).filter(Boolean).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1).filter(Boolean).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      default: s = 3
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1, -1).forEach(line => {
    let [n, s] = line.split(' ')
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1, -1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

print(function(n) {

	var i, j,
		a = [],
		ans = [],
		r = {
			rat: 0,
			woman: 1,
			child: 1,
			man: 2,
			captain: 3
		};

	for (i = 0; i < n; i++) {
		a.push(readline().split(' '));
		a[i][1] = r[a[i][1]];
	}

	for (i = 0; i <= 3; i++)
		for (j = 0; j < n; j++)
			if (a[j][1] === i) ans.push(a[j][0]);

	return ans.join('\n');

}(+readline()));

var n = parseInt(readline())
var t = []
for(var i = 0; i < n; i++){
    var s = readline();
    t.push(s);
}
t = t.map(function(x){
   return x.split(' ');
});
var G = [/rat/, /woman|child/, /^man/, /captain/];
G.forEach(function(reg){
    t.filter(function(x){
        return reg.test(x[1]);
    }).forEach(function(x){
        print(x[0]);
    });
});

;(function () {

    print(function (n) {
        var s = [];
        while (n--) s.push(readline().split(' '));
        n = s.length;

        var r = [];
        for (var i = 0; i < n; i++) if (s[i][1] === 'rat') r.push(s[i][0]);
        for (var i = 0; i < n; i++) if (s[i][1] === 'child' || s[i][1] === 'woman') r.push(s[i][0]);
        for (var i = 0; i < n; i++) if (s[i][1] === 'man') r.push(s[i][0]);
        for (var i = 0; i < n; i++) if (s[i][1] === 'captain') r.push(s[i][0]);

        return r.join('\n');
    }(+readline()));

}.call(this));

'use strict'

let n = +readline()
let ps = [[], [], [], []]

for (let i = 0; i < n; i++) {
  let p = readline().split(' ')
  let n = p[0]
  let s = p[1]
  switch (s) {
    case 'rat': s = 0; break
    case 'woman': s = 1; break
    case 'child': s = 1; break
    case 'man': s = 2; break
    case 'captain': s = 3; break
  }
  ps[s].push(n)
}

let r = []

for (let i = 0; i < 4; i++) {
  for (let j = 0; j < ps[i].length; j++) {
    r.push((ps[i][j]))
  }
}

print(r.join('\n'))

var n = parseInt(readline());

var data = [[], [], [], []];
var res = [];

for (var i = 0; i < n; i++) {
	var inp = readline().split(' ');
	switch(inp[1]) {
		case 'rat':
			data[0].push(inp[0]);
			break;
		case 'woman':
		case 'child':
			data[1].push(inp[0]);
			break;
		case 'man':
			data[2].push(inp[0]);
			break;
		case 'captain':
			data[3].push(inp[0]);
			break;
	}
}

data.forEach(function(arr){
	res = res.concat(arr);
});

res.forEach(function(name) {
	print(name);
});

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else s = 1
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else s = 2
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else if (s == 'child') s = 2
    else s = 3
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = 0
    s = (s + 1) % 4
    ps[s % 4].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach((line, s) => {
    ps[s % 4].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split('\r\n').slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    if (s == 'rat') s = 0
    else if (s == 'woman') s = 1
    else if (s == 'child') s = 1
    else if (s == 'man') s = 2
    else s = 3
    ps[s].push(line)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  input = input.split('\r\n').slice(1)
  console.log(input.join('\n'))
})

'use strict'

const eol = require('os').EOL

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  let ps = [[], [], [], []]

  input.split(eol).slice(1).forEach(line => {
    let p = line.split(' ')
    let n = p[0]
    let s = p[1]
    switch (s) {
      case 'rat': s = 0; break
      case 'woman': s = 1; break
      case 'child': s = 1; break
      case 'man': s = 2; break
      case 'captain': s = 3; break
      default: s = 0
    }
    ps[s].push(n)
  })

  let r = []

  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < ps[i].length; j++) {
      r.push((ps[i][j]))
    }
  }

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  console.log(input)
})

;(function () {

    print(function (n) {
        var s = [];
        while (n--) s.push(readline().split(' '));
        return s.sort(function (a, b) {
            a = typeToNumber(a[1]);
            b = typeToNumber(b[1]);
            return b - a;
        }).map(function (e) {
            return e[0];
        }).join('\n');
    }(+readline()));

    function typeToNumber (type) {
        switch (type) {
            case 'rat': return 100; break;
            case 'child':
            case 'woman': return 50; break;
            case 'man': return 35; break;
            case 'captain': return 0; break;
        }
    }

}.call(this));


Chaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification:   The first box stores toys with fun values in range of $$$(-\infty,-1]$$$.  The second box stores toys with fun values in range of $$$(-1, 0)$$$.  The third box stores toys with fun values in range of $$$(0, 1)$$$.  The fourth box stores toys with fun value in range of $$$[1, \infty)$$$. Chaneka has $$$A$$$, $$$B$$$, $$$C$$$, $$$D$$$ toys in the first, second, third, and fourth box, respectively. One day she decides that she only wants one toy, a super toy. So she begins to create this super toy by sewing all the toys she has.While the number of toys Chaneka has is more than 1, she takes two different toys randomly and then sews them together, creating a new toy. The fun value of this new toy is equal to the multiplication of fun values of the sewn toys. She then puts this new toy in the appropriate box. She repeats this process until she only has one toy. This last toy is the super toy, and the box that stores this toy is the special box.As an observer, you only know the number of toys in each box initially but do not know their fun values. You also don't see the sequence of Chaneka's sewing. Determine which boxes can be the special box after Chaneka found her super toy.

The first line has an integer $$$T$$$ $$$(1 \le T \le 5 \cdot 10^4)$$$, the number of test cases. Every case contains a line with four space-separated integers $$$A$$$ $$$B$$$ $$$C$$$ $$$D$$$ $$$(0 \le A, B, C, D \le 10^6, A + B + C + D > 0)$$$, which denotes the number of toys in the first, second, third, and fourth box, respectively.

For each case, print four space-separated strings. Each string represents the possibility that the first, second, third, and fourth box can be the special box from left to right. For each box, print "Ya" (Without quotes, Indonesian for yes) if that box can be the special box. Print "Tidak" (Without quotes, Indonesian for No) otherwise.

NoteFor the first case, here is a scenario where the first box is the special box:   The first box had toys with fun values $$$\{-3\}$$$.  The second box had toys with fun values $$$\{ -0.5, -0.5 \}$$$  The fourth box had toys with fun values $$$\{ 3 \}$$$ The sewing sequence:   Chaneka sews the toy with fun $$$-0.5$$$ and $$$-0.5$$$ to a toy with fun $$$0.25$$$ and then put it in the third box.  Chaneka sews the toy with fun $$$-3$$$ and $$$0.25$$$ to a toy with fun $$$-0.75$$$ and then put it in the second box.  Chaneka sews the toy with fun $$$-0.75$$$ and $$$3$$$ to a toy with fun $$$-1.25$$$ and then put it in the first box, which then became the special box. Here is a scenario where the second box ends up being the special box:   The first box had toys with fun values $$$\{-3\}$$$  The second box had toys with fun values $$$\{ -0.33, -0.25 \}$$$.  The fourth box had toys with fun values $$$\{ 3 \}$$$. The sewing sequence:   Chaneka sews the toy with fun $$$-3$$$ and $$$-0.33$$$ to a toy with fun $$$0.99$$$ and then put it in the third box.  Chaneka sews the toy with fun $$$0.99$$$ and $$$3$$$ to a toy with fun $$$2.97$$$ and then put in it the fourth box.  Chaneka sews the toy with fun $$$2.97$$$ and $$$-0.25$$$ to a toy with fun $$$-0.7425$$$ and then put it in the second box, which then became the special box.  There is only one toy for the second case, so Chaneka does not have to sew anything because that toy, by definition, is the super toy.

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 a = ti(readline().split(' '));
        let res = new Array(4);
        if((a[0] + a[1]) % 2 !== 0){
            res[2] = res[3] = 'Tidak';
            res[0] = (a[3] !== 0 || a[0] !== 0) ? 'Ya' : 'Tidak';
            res[1] = (a[2] !== 0 || a[1] !== 0) ? 'Ya' : 'Tidak';
        }else{
            res[0] = res[1] = 'Tidak'
            res[2] = (a[2] !== 0 || a[1] !== 0) ? 'Ya' : 'Tidak';
            res[3] = (a[3] !== 0 || a[0] !== 0) ? 'Ya' : 'Tidak';
        }

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

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 a = ti(readline().split(' '));
        let res = new Array(4);
        if((a[0] + a[1]) % 2 !== 0){
            res[2] = res[3] = 'Tidak';
            res[0] = (a[3] !== 0 || a[0] !== 0) ? 'Ya' : 'TTidak';
            res[1] = (a[2] !== 0 || a[1] !== 0) ? 'Ya' : 'TTidak';
        }else{
            res[0] = res[1] = 'Tidak'
            res[2] = (a[2] !== 0 || a[1] !== 0) ? 'Ya' : 'TTidak';
            res[3] = (a[3] !== 0 || a[0] !== 0) ? 'Ya' : 'TTidak';
        }

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


One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $$$n$$$ machines, and the power of the $$$i$$$-th machine is $$$a_i$$$. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $$$x$$$, then choose one machine and reduce the power of its machine by $$$x$$$ times, and at the same time increase the power of one another machine by $$$x$$$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $$$i$$$ and $$$j$$$, and one integer $$$x$$$ such that $$$x$$$ is a divisor of $$$a_i$$$, and change powers as following: $$$a_i = \frac{a_i}{x}$$$, $$$a_j = a_j \cdot x$$$Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — the number of machines. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the powers of the machines.

Print one integer — minimum total power.

NoteIn the first example, the farmer can reduce the power of the $$$4$$$-th machine by $$$2$$$ times, and increase the power of the $$$1$$$-st machine by $$$2$$$ times, then the powers will be: $$$[2, 2, 3, 2, 5]$$$.In the second example, the farmer can reduce the power of the $$$3$$$-rd machine by $$$2$$$ times, and increase the power of the $$$2$$$-nd machine by $$$2$$$ times. At the same time, the farmer can leave is be as it is and the total power won't change.In the third example, it is optimal to leave it be as it is.

var n = parseInt(readline())
var p = readline().split(' ').map((v)=>(parseInt(v))).sort((a, b)=>(a-b));

var init = 0;
p.forEach((v)=>(init+=v))
var best = init;

function sol(index, d) {

    var old1=p[0]  , old2=p[index];
    var new1=p[0]*d, new2=p[index]/d;

    // print(p.join(','))
    // print(old1, ' => ', new1)
    // print(old2, ' => ', new2)

    var cur = init - old1 - old2 + new1 + new2;

    best = Math.min(best, cur)
}

for(var i=0; i<p.length; i++) {
    var t = p[i];
    sol(i, p[i])
    if (p[i]%2===0) {
        sol(i, 2)
    }
    for(var j=3; j*j<=p[i]; j++) {
        if (p[i]%j === 0) {
            sol(i, j)
            sol(i, p[i]/j)
        }
    }
}

print(best)

var n = parseInt(readline())
var p = readline().split(' ').map((v)=>(parseInt(v))).sort((a, b)=>(a-b));

var init = 0;
p.forEach((v)=>(init+=v))
var best = init;

function sol(index, d) {

    var old1=p[0]  , old2=p[index];
    var new1=p[0]*d, new2=p[index]/d;

    // print(p.join(','))
    // print(old1, ' => ', new1)
    // print(old2, ' => ', new2)

    var cur = init - old1 - old2 + new1 + new2;

    best = Math.min(best, cur)
}

for(var i=0; i<p.length; i++) {
    var t = p[i];
    if (p[i]%2===0) {
        sol(i, 2)
    }
    for(var j=3; j<=p[i]; j+=2) {
        if (p[i]%j === 0) {
            sol(i, j)
        }
    }
}

print(best)


This is the hard version of the problem. The only difference is that in this version $$$n \leq 200000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 200000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point

'use strict';

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, a) {
  let t = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] >= 0) {
      t = i;
      break;
    }
  }
  if (t === -1) return 0;
  const dp = new Array(n).fill(0);
  const heap = new Heap((a, b) => a - b);
  let sum = 0;
  for (let i = t; i < n; i++) {
    var _dp;
    if (a[i] < 0) heap.push(a[i]);
    sum += a[i];
    dp[i] = ((_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    while (sum < 0) {
      sum -= heap.pop();
      dp[i]--;
    }
  }
  let res = 0;
  for (let i = 0; i < n; i++) {
    res = Math.max(res, dp[i]);
  }
  return res;
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

// PriorityQueue implementated using array based binary heap
// PriorityQueue methods
//  push(...values)
// 	peek()
//  pop()
//  size()
//  replace(value)

class PriorityQueue {

	constructor(comparator = (a, b) => a > b) {
		this.top = 0;
		this._heap = [];
		this._comparator = comparator;
	}
	size() {
		return this._heap.length;
	}
	isEmpty() {
		return this.size() == 0;
	}
	peek() {
		return this._heap[this.top];
	}
	push(...values) {
		values.forEach(value => {
				this._heap.push(value);
				this._siftUp();
				});
		return this.size();
	}
	pop() {
		const poppedValue = this.peek();
		const bottom = this.size() - 1;
		if (bottom > this.top) {
			this._swap(this.top, bottom);
		}
		this._heap.pop();
		this._siftDown();
		return poppedValue;
	}
	replace(value) {
		const replacedValue = this.peek();
		this._heap[this.top] = value;
		this._siftDown();
		return replacedValue;
	}
	_greater(i, j) {
		return this._comparator(this._heap[i], this._heap[j]);
	}
	_swap(i, j) {
		[this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
	}
	_siftUp() {
		const parent = i => ((i + 1) >>> 1) - 1;
		let node = this.size() - 1;
		while (node > this.top && this._greater(node, parent(node))) {
			this._swap(node, parent(node));
			node = parent(node);
		}
	}
	_siftDown() {
		const left = i => (i << 1) + 1;
		const right = i => (i + 1) << 1;
		let node = this.top;
		while (
				(left(node) < this.size() && this._greater(left(node), node)) ||
				(right(node) < this.size() && this._greater(right(node), node))
			  ) {
			let maxChild = (right(node) < this.size() && this._greater(right(node), left(node))) ? right(node) : left(node);
			this._swap(node, maxChild);
			node = maxChild;
		}
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	const n = rn();
	const a = rna();

	let health = 0, used = 0;
	const q = new PriorityQueue((a, b) => a > b);
	for (let i = 0; i < n; i++) {
		if (a[i] >= 0) {
			health += a[i];
			used++;
		} else {
			a[i] = -a[i];
			if (health - a[i] >= 0) {
				health -= a[i];
				q.push(a[i]);
				used++;
			} else {
				if (a[i] < q.peek()) {
					health += q.pop() - a[i];
					q.push(a[i]);
				}
			}
		}
	}

	console.log(used);
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 05/28/21 night

const solve = (n, a) => {
    let pq = new MinPriorityQueue({ priority: x => x });
    let res = sum = 0;
    for (const e of a) {
        sum += e;
        res++;
        if (e < 0) {
            pq.enqueue(e);
            while (sum < 0) {
                sum -= pq.dequeue().element;
                res--;
            }
        }
    }
    pr(res);
};

class HeapNode {
    constructor(key, value) {
        this._key = key;
        this._value = value;
    }

    getKey() {
        return this._key;
    }

    getValue() {
        return this._value;
    }
}

const isNumber = (n) => typeof n === 'number';
const isNoneEmptyString = (s) => typeof s === 'string' && s.length;
const isNoneNullObject = (o) => typeof o === 'object' && o !== null;
const isNoneEmptyArray = (a) => Array.isArray(a) && a.length > 0;

class Heap {
    constructor(nodes) {
        this._nodes = Array.isArray(nodes) ? nodes : [];
        this._leaf = null;
    }

    _getLeftChildIndex(parentIndex) {
        return (parentIndex * 2) + 1;
    }

    _getRightChildIndex(parentIndex) {
        return (parentIndex * 2) + 2;
    }

    _getParentIndex(childIndex) {
        return Math.floor((childIndex - 1) / 2);
    }

    _getLastIndex() {
        return this._nodes.length - 1;
    }

    _swap(i, j) {
        const temp = this._nodes[i];
        this._nodes[i] = this._nodes[j];
        this._nodes[j] = temp;
    }

    _compareChildrenOf(parentIndex) {
        const leftChildIndex = this._getLeftChildIndex(parentIndex);
        const rightChildIndex = this._getRightChildIndex(parentIndex);
        const size = this.size();
        if (leftChildIndex >= size && rightChildIndex >= size) return -1;
        if (leftChildIndex >= size) return rightChildIndex;
        if (rightChildIndex >= size) return leftChildIndex;
        return this._compareChildren(leftChildIndex, rightChildIndex);
    }

    _heapifyUp() {
        let childIndex = this._getLastIndex();
        let parentIndex = this._getParentIndex(childIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            childIndex = parentIndex;
            parentIndex = this._getParentIndex(childIndex);
        }
    }

    _heapifyDown() {
        let parentIndex = 0;
        let childIndex = this._compareChildrenOf(parentIndex);
        while (this._shouldSwap(childIndex, parentIndex)) {
            this._swap(childIndex, parentIndex);
            parentIndex = childIndex;
            childIndex = this._compareChildrenOf(parentIndex);
        }
    }

    _heapifyDownUntil(index) {
        let parentIndex = 0;
        let leftChildIndex = 1;
        let rightChildIndex = 2;
        let childIndex;
        while (leftChildIndex < index) {
            childIndex = this._compareChildrenBefore(
                index,
                leftChildIndex,
                rightChildIndex
            );
            if (this._shouldSwap(childIndex, parentIndex)) {
                this._swap(childIndex, parentIndex);
            }
            parentIndex = childIndex;
            leftChildIndex = this._getLeftChildIndex(parentIndex);
            rightChildIndex = this._getRightChildIndex(parentIndex);
        }
    }

    _clone(HeapType) {
        return new HeapType(this._nodes.slice());
    }

    sort() {
        for (let i = this._getLastIndex(); i > 0; i -= 1) {
            this._swap(0, i);
            this._heapifyDownUntil(i);
        }
        return this._nodes;
    }

    insert(key, value) {
        const newNode = new HeapNode(key, value);
        this._nodes.push(newNode);
        this._heapifyUp();
        return newNode;
    }

    root() {
        if (this.isEmpty()) return null;
        return this._nodes[0];
    }

    leaf() {
        return this._leaf;
    }

    extractRoot() {
        if (this.isEmpty()) return null;
        const root = this.root();
        this._nodes[0] = this._nodes[this._getLastIndex()];
        this._nodes.pop();
        this._heapifyDown();
        if (root === this._leaf) {
            if (this.isEmpty()) {
                this._leaf = null;
            } else {
                this._leaf = this.root();
            }
        }
        return root;
    }

    size() {
        return this._nodes.length;
    }

    isEmpty() {
        return this.size() === 0;
    }

    clear() {
        this._nodes = [];
        this._leaf = null;
    }

    static _heapify(items, HeapType) {
        if (!isNoneEmptyArray(items)) return null;
        const heap = new HeapType();
        items.forEach((item) => {
            if (isNumber(item) || isNoneEmptyString(item)) {
                heap.insert(item);
            } else if (isNoneNullObject(item) &&
                (isNumber(item.key) || isNoneEmptyString(item.key))) {
                heap.insert(item.key, item.value);
            }
        });
        return heap;
    }
}

class MinHeap extends Heap {
    _getMinChildIndex(leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (leftChild.getKey() < rightChild.getKey()) {
            return leftChildIndex;
        }
        return rightChildIndex;
    }

    _getMinChildIndexBefore(index, leftChildIndex, rightChildIndex) {
        const leftChild = this._nodes[leftChildIndex];
        const rightChild = this._nodes[rightChildIndex];
        if (rightChild.getKey() < leftChild.getKey() && rightChildIndex < index) {
            return rightChildIndex;
        }
        return leftChildIndex;
    }

    _shouldSwap(childIndex, parentIndex) {
        if (childIndex < 0 || childIndex >= this.size()) return false;
        if (parentIndex < 0 || parentIndex >= this.size()) return false;
        const child = this._nodes[childIndex];
        const parent = this._nodes[parentIndex];
        return child.getKey() < parent.getKey();
    }

    _compareChildren(leftChildIndex, rightChildIndex) {
        return this._getMinChildIndex(leftChildIndex, rightChildIndex);
    }

    _compareChildrenBefore(index, leftChildIndex, rightChildIndex) {
        return this._getMinChildIndexBefore(index, leftChildIndex, rightChildIndex);
    }

    insert(key, value) {
        const newNode = super.insert(key, value);
        if (this._leaf === null || key > this._leaf.getKey()) {
            this._leaf = newNode;
        }
        return newNode;
    }

    clone() {
        return super._clone(MinHeap);
    }

    static heapify(items) {
        return super._heapify(items, MinHeap);
    }
}

class PriorityQueue {
    constructor(options = {}) {
        const {
            priority
        } = options;
        if (priority !== undefined && typeof priority !== 'function') {
            throw new Error('invalid priority callback');
        }
        this._getPriority = typeof priority === 'function' ? priority : null;
    }

    size() {
        return this._heap.size();
    }

    isEmpty() {
        return this._heap.isEmpty();
    }

    front() {
        if (this.isEmpty()) return null;
        const first = this._heap.root();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    back() {
        if (this.isEmpty()) return null;
        const last = this._heap.leaf();
        return {
            priority: last.getKey(),
            element: last.getValue()
        };
    }

    enqueue(element, p) {
        if (p && Number.isNaN(+p)) {
            throw new Error('invalid priority number');
        }
        if (Number.isNaN(+p) && this._getPriority === null) {
            throw new Error('missing priority number or constructor callback');
        }
        const priority = !Number.isNaN(+p) ? p : this._getPriority(element);
        this._heap.insert(priority, element);
    }

    dequeue() {
        if (this.isEmpty()) return null;
        const first = this._heap.extractRoot();
        return {
            priority: first.getKey(),
            element: first.getValue()
        };
    }

    toArray() {
        return this._heap
            .clone()
            .sort()
            .map((n) => ({
                priority: n.getKey(),
                element: n.getValue()
            }))
            .reverse();
    }

    clear() {
        this._heap.clear();
    }
}

class MinPriorityQueue extends PriorityQueue {
    constructor(options) {
        super(options);
        this._heap = new MinHeap();
    }
}

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        solve(input[0][0], input[1]);
    });
};

main()


Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up.

First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$.

Print the only integer — maximum possible total time when the lamp is lit.

NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$.

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString='';
let currentLine=0;
process.stdin.on('data',inputStdin=>{
    inputString+=inputStdin;
});
process.stdin.on('end',_=>{
    inputString=inputString.trim().split("\n").map(string=>{
        return string.trim();
    });
    main();
});
function readLine()
{
    return inputString[currentLine++];
}
function main()
{
    const [N,M]=readLine().trim().split(' ').map(x=>{return +(x);});
    let A=readLine().trim().split(' ').map(x=>{return +(x);});
    A.unshift(0);
    A.push(M);
    let zer=[],zerc=0,on=[],onc=0;
    //console.log(A);
    for(let i=0;i<=N;i++)
    {
        if(i&1)
        {
            on.push(A[i+1]-A[i]);
            ++onc;
            if(i!=1)
            {
                on[onc-1]+=on[onc-2];
            }
        }
        else
        {
            zer.push(A[i+1]-A[i]);
            ++zerc;
            if(i!==0)
            {
                zer[zerc-1]+=zer[zerc-2];
            }
        }
    }
    zer.unshift(0);
    on.unshift(0);
    ++zerc;
    ++onc;
    //console.log(zer);
    //console.log(on);
    let m=zer[zerc-1];
    for(let i=0;i<=N;++i)
    {
        if(A[i+1]-A[i]>1)
        {
            let t=zer[Math.floor((i+1)/2)]+A[i+1]-A[i]-1-on[Math.floor((i+1)/2)]+on[onc-1];
            //console.log(t);
            if(t>m)
            {
                m=t;
            }
            t=zer[Math.floor((i+1)/2)]+1-on[Math.floor((i+1)/2)]+on[onc-1];
            //console.log(t);
            if(t>m)
            {
                m=t;
            }
        }
    }
    console.log(m);
}

function readInts() {
    return readline().split(' ').map(function (v) { return parseInt(v); });
}
function solve(n, m, a) {
    var _a, _b;
    var _c = [0, 0, 0, 0], on = _c[0], off = _c[1], xon = _c[2], xoff = _c[3];
    var max = m;
    var i = n - 1;
    while (i >= -1) {
        var ai = i >= 0 ? a[i] : 0;
        var l = max - ai;
        _a = [l + xoff, xon], xon = _a[0], xoff = _a[1];
        if (l > 1) {
            var _d = [l - 1 + on, l - 1 + off], nxon = _d[0], nxoff = _d[1];
            if (nxon > xon)
                xon = nxon;
            if (nxoff > xoff)
                xoff = nxoff;
        }
        _b = [l + off, on], on = _b[0], off = _b[1];
        max = ai;
        // console.log({i,max,l,on,off,xon,xoff});
        i--;
    }
    return xon > on ? xon : on;
}
// function show(n: number, m: number, a: number[]) {
//     console.log(n, m, a, '-->', solve(n, m, a));
// }
// show(3, 10, [4, 6, 7]);
// show(2, 12, [1, 10]);
// show(2, 7, [3, 4]);
var _a = readInts(), n = _a[0], m = _a[1];
var a = readInts();
print(solve(n, m, a));

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

  var a = [0].concat(readline().split(' ').map(x => parseInt(x)), m);
  n += 2;
  var s = [0];
  for(var i = 1; i < n; i += 1) {
    if(i % 2 === 1) {
      s[i] = s[i - 1] + a[i] - a[i - 1];
    } else {
      s[i] = s[i - 1];
    }
  }
  var sr = [a[1]];
  for(var i = 1; i < n; i += 1) {
    if(i % 2 === 0) {
      sr[i] = sr[i - 1] + a[i] - a[i - 1];
    } else {
      sr[i] = sr[i - 1];
    }
  }
  var mx = -1;
  mx = Math.max(mx, s[n - 1]);
  for(var i = 0; i < n; i += 1) {
    if(i % 2 === 0) {
      if(i !== 0) {
        if(a[i - 1] !== a[i] - 1) {
          var res = s[i - 1];
          res += a[i] - a[i - 1] - 1;
          res += sr[n - 1] - sr[i];
          mx = Math.max(mx, res);
          // console.log(a[i - 1] + 1, res);
        }
      }
    } else {
      if(a[i - 1] + 1 !== a[i]) {
        var res = s[i - 1];
        res += a[i] - a[i - 1] - 1;
        res += sr[n - 1] - sr[i];
        mx = Math.max(mx, res);
        // console.log(a[i - 1] + 1, res);
      }
    }
  }
  // console.log(a);
  // console.log(s);
  // console.log(sr);
  print(mx);


You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \le a, b \le 10^9$$$).

For each test case print the answer to it — YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero:  choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$;  choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$.

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

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

    if((a + b) % 3 == 0 && a >= b && a <= 2 * b) {
      console.log('YES')
    }
    else if((a + b) % 3 == 0 && a <= b && b <= 2 * a) {
      console.log('YES')
    }
    else {
      console.log('NO')
    }
  }
})

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

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if((a+b)%3 !== 0) valid = false;
    else if((a+b)/3 > a || (a+b)/3 > b) valid = false;

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

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

    if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0)) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a>b) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b>=a && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        } else if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        }
    }
}

var t = parseInt(readline(), 10);

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

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0) || a === 0 || b === 0) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        } else if(a_cpy === 0 || b_cpy === 0) {
            print('NO');
        } else if(a_cpy>b_cpy) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b_cpy>=a_cpy && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        }
    }
}

var t = parseInt(readline(), 10);

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

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0) || a === 0 || b === 0) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        } else if(a_cpy>b_cpy) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b_cpy>=a_cpy && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        }
    }
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if(a===0 && b===0) {
        valid = true;

    } else if(a===0 || b===0) {
        valid = false;

    } else if(a>b) {
        div = Math.floor(a/2);

        if(div < b) {
            a -= 2*div;
            b -= div;

            if(a!==1 || b!==2) valid = false;

        } else if(div === b && a%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }

    } else {
        div = Math.floor(b/2);

        if(div < a) {
            b -= 2*div;
            a -= div;

            if(b!==1 || a!==2) valid = false;

        } else if(div === a && b%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }
    }

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if(a===0 && b===0) {
        valid = true;

    } else if(a===0 || b===0 || a===b) {
        valid = false;

    } else if(a>b) {
        div = Math.floor(a/2);

        if(div < b) {
            a -= 2*div;
            b -= div;

            if(a!==1 || b!==2) valid = false;

        } else if(div === b && a%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }

    } else {
        div = Math.floor(b/2);

        if(div < a) {
            b -= 2*div;
            a -= div;

            if(b!==1 || a!==2) valid = false;

        } else if(div === a && b%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }
    }

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

while(t--) {
    var inp = readline().split(' ');
    var a = parseInt(inp[0], 10), b = parseInt(inp[1], 10), div = 0, valid = true;

    if(a===0 || b===0 || a===b) {
        valid = false;

    } else if(a>b) {
        div = Math.floor(a/2);

        if(div < b) {
            a -= 2*div;
            b -= div;

            if(a!==1 || b!==2) valid = false;

        } else if(div === b && a%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }

    } else {
        div = Math.floor(b/2);

        if(div < a) {
            b -= 2*div;
            a -= div;

            if(b!==1 || a!==2) valid = false;

        } else if(div === a && b%2 === 0) {
            valid = true;

        } else {
            valid = false;
        }
    }

    print(valid ? 'YES' : 'NO');
}

var t = parseInt(readline(), 10);

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

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 !== 0 && b%2 !== 0) || a === 0 || b === 0) {
        print('NO');

    } else {
        if(a%2 === 0 && b%2 === 0) {
            if(a>b) {
                a_cpy -= 2;
                b_cpy -= 1;
            } else {
                a_cpy -= 1;
                b_cpy -= 2;
            }

        } else if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        } else if(a_cpy === 0 || b_cpy === 0) {
            print('NO');
        } else if(a_cpy>b_cpy) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b_cpy>=a_cpy && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        }
    }
}

var t = parseInt(readline(), 10);

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

    if(a === 0 && b === 0) {
        print('YES');

    } else if(a === b || (a%2 === 0 && b%2 === 0) || (a%2 !== 0 && b%2 !== 0)) {
        print('NO');

    } else {
        if(a%2 === 0) {
            a_cpy -= 2;
            b_cpy -= 1;

        } else {
            a_cpy -= 1;
            b_cpy -= 2;

        }

        if(a>b) {
            if(a_cpy%b_cpy === 0) print('YES');
            else print('NO');

        } else if(b>=a && (a_cpy !== 0 && b_cpy !== 0)) {
            if(b_cpy%a_cpy === 0) print('YES');
            else print('NO');

        } else if(a_cpy === 0 && b_cpy === 0) {
            print('YES');

        }
    }
}


In all schools in Buryatia, in the $$$1$$$ class, everyone is told the theory of Fibonacci strings."A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci string if, when it is divided into blocks, their lengths in the order they appear in the string form the Fibonacci sequence ($$$f_0 = f_1 = 1$$$, $$$f_i = f_{i-2} + f_{i-1}$$$), starting from the zeroth member of this sequence. A string is called semi-Fibonacci if it possible to reorder its letters to get a Fibonacci string."Burenka decided to enter the Buryat State University, but at the entrance exam she was given a difficult task. She was given a string consisting of the letters of the Buryat alphabet (which contains exactly $$$k$$$ letters), and was asked if the given string is semi-Fibonacci. The string can be very long, so instead of the string, she was given the number of appearances of each letter ($$$c_i$$$ for the $$$i$$$-th letter) in that string. Unfortunately, Burenka no longer remembers the theory of Fibonacci strings, so without your help she will not pass the exam.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The first line of each test case contains one integer $$$k$$$ ($$$1 \leq k \leq 100$$$) — the number of letters in the alphabet. The second line of each test case contains $$$k$$$ integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \leq c_i \leq 10^9$$$) — the number of occurrences of each letter in the string.

For each test case print the string "YES" if the corresponding string is semi-Fibonacci, and "NO" if it is not. You can print "YES" and "NO" in any case (for example, the strings "yEs", "yes", "Yes" will be recognized as a positive answer).

NoteIn the first test case, a one-character string is semi-Fibonacci, being itself a Fibonacci string.In the second test case, a string of two different characters is Fibonacci.In the third test case, the string "abb" (let the first of the alphabet letter be a, the second letter b) is not a semi-Fibonacci string, since no permutation of its letters ("abb", "bab", and "bba") is a Fibonacci string.In the fourth test case, two permutations of the letters of the string "abaccac" (the first letter is a, the second letter is b, the third letter is c) are Fibonacci strings — "abaaccc" and "cbccaaa".

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr) ? 'YES' : 'NO'
    }
    console.log(output.join('\n'))
// })()
})
// Generated by CoffeeScript 1.8.0
;(function() {
  var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;

  floor = Math.floor, min = Math.min;

  /*
  Default comparison function to be used
   */

  defaultCmp = function(x, y) {
    if (x < y) {
      return -1;
    }
    if (x > y) {
      return 1;
    }
    return 0;
  };

  /*
  Insert item x in list a, and keep it sorted assuming a is sorted.

  If x is already in a, insert it to the right of the rightmost x.

  Optional args lo (default 0) and hi (default a.length) bound the slice
  of a to be searched.
   */

  insort = function(a, x, lo, hi, cmp) {
    var mid;
    if (lo == null) {
      lo = 0;
    }
    if (cmp == null) {
      cmp = defaultCmp;
    }
    if (lo < 0) {
      throw new Error('lo must be non-negative');
    }
    if (hi == null) {
      hi = a.length;
    }
    while (lo < hi) {
      mid = floor((lo + hi) / 2);
      if (cmp(x, a[mid]) < 0) {
        hi = mid;
      } else {
        lo = mid + 1;
      }
    }
    return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
  };

  /*
  Push item onto heap, maintaining the heap invariant.
   */

  heappush = function(array, item, cmp) {
    if (cmp == null) {
      cmp = defaultCmp;
    }
    array.push(item);
    return _siftdown(array, 0, array.length - 1, cmp);
  };

  /*
  Pop the smallest item off the heap, maintaining the heap invariant.
   */

  heappop = function(array, cmp) {
    var lastelt, returnitem;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    lastelt = array.pop();
    if (array.length) {
      returnitem = array[0];
      array[0] = lastelt;
      _siftup(array, 0, cmp);
    } else {
      returnitem = lastelt;
    }
    return returnitem;
  };

  /*
  Pop and return the current smallest value, and add the new item.

  This is more efficient than heappop() followed by heappush(), and can be
  more appropriate when using a fixed size heap. Note that the value
  returned may be larger than item! That constrains reasonable use of
  this routine unless written as part of a conditional replacement:
      if item > array[0]
        item = heapreplace(array, item)
   */

  heapreplace = function(array, item, cmp) {
    var returnitem;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    returnitem = array[0];
    array[0] = item;
    _siftup(array, 0, cmp);
    return returnitem;
  };

  /*
  Fast version of a heappush followed by a heappop.
   */

  heappushpop = function(array, item, cmp) {
    var _ref;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    if (array.length && cmp(array[0], item) < 0) {
      _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
      _siftup(array, 0, cmp);
    }
    return item;
  };

  /*
  Transform list into a heap, in-place, in O(array.length) time.
   */

  heapify = function(array, cmp) {
    var i, _i, _j, _len, _ref, _ref1, _results, _results1;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    _ref1 = (function() {
      _results1 = [];
      for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
      return _results1;
    }).apply(this).reverse();
    _results = [];
    for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
      i = _ref1[_i];
      _results.push(_siftup(array, i, cmp));
    }
    return _results;
  };

  /*
  Update the position of the given item in the heap.
  This function should be called every time the item is being modified.
   */

  updateItem = function(array, item, cmp) {
    var pos;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    pos = array.indexOf(item);
    if (pos === -1) {
      return;
    }
    _siftdown(array, 0, pos, cmp);
    return _siftup(array, pos, cmp);
  };

  /*
  Find the n largest elements in a dataset.
   */

  nlargest = function(array, n, cmp) {
    var elem, result, _i, _len, _ref;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    result = array.slice(0, n);
    if (!result.length) {
      return result;
    }
    heapify(result, cmp);
    _ref = array.slice(n);
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      elem = _ref[_i];
      heappushpop(result, elem, cmp);
    }
    return result.sort(cmp).reverse();
  };

  /*
  Find the n smallest elements in a dataset.
   */

  nsmallest = function(array, n, cmp) {
    var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    if (n * 10 <= array.length) {
      result = array.slice(0, n).sort(cmp);
      if (!result.length) {
        return result;
      }
      los = result[result.length - 1];
      _ref = array.slice(n);
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        elem = _ref[_i];
        if (cmp(elem, los) < 0) {
          insort(result, elem, 0, null, cmp);
          result.pop();
          los = result[result.length - 1];
        }
      }
      return result;
    }
    heapify(array, cmp);
    _results = [];
    for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
      _results.push(heappop(array, cmp));
    }
    return _results;
  };

  _siftdown = function(array, startpos, pos, cmp) {
    var newitem, parent, parentpos;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    newitem = array[pos];
    while (pos > startpos) {
      parentpos = (pos - 1) >> 1;
      parent = array[parentpos];
      if (cmp(newitem, parent) < 0) {
        array[pos] = parent;
        pos = parentpos;
        continue;
      }
      break;
    }
    return array[pos] = newitem;
  };

  _siftup = function(array, pos, cmp) {
    var childpos, endpos, newitem, rightpos, startpos;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    endpos = array.length;
    startpos = pos;
    newitem = array[pos];
    childpos = 2 * pos + 1;
    while (childpos < endpos) {
      rightpos = childpos + 1;
      if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
        childpos = rightpos;
      }
      array[pos] = array[childpos];
      pos = childpos;
      childpos = 2 * pos + 1;
    }
    array[pos] = newitem;
    return _siftdown(array, startpos, pos, cmp);
  };

  Heap = (function() {
    Heap.push = heappush;

    Heap.pop = heappop;

    Heap.replace = heapreplace;

    Heap.pushpop = heappushpop;

    Heap.heapify = heapify;

    Heap.updateItem = updateItem;

    Heap.nlargest = nlargest;

    Heap.nsmallest = nsmallest;

    function Heap(cmp) {
      this.cmp = cmp != null ? cmp : defaultCmp;
      this.nodes = [];
    }

    Heap.prototype.push = function(x) {
      return heappush(this.nodes, x, this.cmp);
    };

    Heap.prototype.pop = function() {
      return heappop(this.nodes, this.cmp);
    };

    Heap.prototype.peek = function() {
      return this.nodes[0];
    };

    Heap.prototype.contains = function(x) {
      return this.nodes.indexOf(x) !== -1;
    };

    Heap.prototype.replace = function(x) {
      return heapreplace(this.nodes, x, this.cmp);
    };

    Heap.prototype.pushpop = function(x) {
      return heappushpop(this.nodes, x, this.cmp);
    };

    Heap.prototype.heapify = function() {
      return heapify(this.nodes, this.cmp);
    };

    Heap.prototype.updateItem = function(x) {
      return updateItem(this.nodes, x, this.cmp);
    };

    Heap.prototype.clear = function() {
      return this.nodes = [];
    };

    Heap.prototype.empty = function() {
      return this.nodes.length === 0;
    };

    Heap.prototype.size = function() {
      return this.nodes.length;
    };

    Heap.prototype.clone = function() {
      var heap;
      heap = new Heap();
      heap.nodes = this.nodes.slice(0);
      return heap;
    };

    Heap.prototype.toArray = function() {
      return this.nodes.slice(0);
    };

    Heap.prototype.insert = Heap.prototype.push;

    Heap.prototype.top = Heap.prototype.peek;

    Heap.prototype.front = Heap.prototype.peek;

    Heap.prototype.has = Heap.prototype.contains;

    Heap.prototype.copy = Heap.prototype.clone;

    return Heap;

  })();

  (function(root, factory) {
    // if (typeof define === 'function' && define.amd) {
    //   return define([], factory);
    // } else if (typeof exports === 'object') {
    //   return module.exports = factory();
    // } else {
      return root.Heap = factory();
    // }
  })(this, function() {
    return Heap;
  });

}).call(this);

const Heap = this.Heap

let dp
const cache = pre()
function pre() {
    dp = [1, 1]
    let i = 2
    let sum = dp[0] + dp[1]
    const m = {}
    m[1] = 1
    m[2] = 2
    while (1) {
        dp[i] = dp[i - 1] + dp[i - 2]
        sum += dp[i]
        if (dp[i] > 1e9) break
        m[sum] = ++i
    }
    return m
}
function solve(n, arr) {
    const sum = arr.reduce((s, x) => s + x, 0)
    const m = cache[sum]
    if (!m) return false

    const h = new Heap((a, b) => b - a)
    h.nodes = arr
    h.heapify()
    let i = m - 1
    let temp
    while (i >= 0) {
        if (!h.size()) return false
            // console.log(h.nodes, dp[i], temp)
        let x = h.pop()
        if (x < dp[i]) return false
            // console.log(dp[i])
        x -= dp[i--]
        if (temp) {
            h.push(temp)
            temp = 0
        }
        if (x > 0) temp = x
    }
    return true
}


You are given $$$m$$$ sets of integers $$$A_1, A_2, \ldots, A_m$$$; elements of these sets are integers between $$$1$$$ and $$$n$$$, inclusive.There are two arrays of positive integers $$$a_1, a_2, \ldots, a_m$$$ and $$$b_1, b_2, \ldots, b_n$$$. In one operation you can delete an element $$$j$$$ from the set $$$A_i$$$ and pay $$$a_i + b_j$$$ coins for that.You can make several (maybe none) operations (some sets can become empty).After that, you will make an edge-colored undirected graph consisting of $$$n$$$ vertices. For each set $$$A_i$$$ you will add an edge $$$(x, y)$$$ with color $$$i$$$ for all $$$x, y \in A_i$$$ and $$$x < y$$$. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.You call a cycle $$$i_1 \to e_1 \to i_2 \to e_2 \to \ldots \to i_k \to e_k \to i_1$$$ ($$$e_j$$$ is some edge connecting vertices $$$i_j$$$ and $$$i_{j+1}$$$ in this graph) rainbow if all edges on it have different colors.Find the minimum number of coins you should pay to get a graph without rainbow cycles.

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \leq m, n \leq 10^5$$$), the number of sets and the number of vertices in the graph. The second line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \leq a_i \leq 10^9$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$). In the each of the next of $$$m$$$ lines there are descriptions of sets. In the $$$i$$$-th line the first integer $$$s_i$$$ ($$$1 \leq s_i \leq n$$$) is equal to the size of $$$A_i$$$. Then $$$s_i$$$ integers follow: the elements of the set $$$A_i$$$. These integers are from $$$1$$$ to $$$n$$$ and distinct. It is guaranteed that the sum of $$$s_i$$$ for all $$$1 \leq i \leq m$$$ does not exceed $$$2 \cdot 10^5$$$.

Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.

NoteIn the first test, you can make such operations:  Delete element $$$1$$$ from set $$$1$$$. You should pay $$$a_1 + b_1 = 5$$$ coins for that.  Delete element $$$1$$$ from set $$$2$$$. You should pay $$$a_2 + b_1 = 6$$$ coins for that. You pay $$$11$$$ coins in total. After these operations, the first and the second sets will be equal to $$$\{2\}$$$ and the third set will be equal to $$$\{1, 2\}$$$.So, the graph will consist of one edge $$$(1, 2)$$$ of color $$$3$$$.In the second test, you can make such operations:  Delete element $$$1$$$ from set $$$1$$$. You should pay $$$a_1 + b_1 = 11$$$ coins for that.  Delete element $$$4$$$ from set $$$2$$$. You should pay $$$a_2 + b_4 = 13$$$ coins for that.  Delete element $$$7$$$ from set $$$3$$$. You should pay $$$a_3 + b_7 = 13$$$ coins for that.  Delete element $$$4$$$ from set $$$4$$$. You should pay $$$a_4 + b_4 = 16$$$ coins for that.  Delete element $$$7$$$ from set $$$6$$$. You should pay $$$a_6 + b_7 = 13$$$ coins for that. You pay $$$66$$$ coins in total.After these operations, the sets will be:  $$$\{2, 3\}$$$;  $$$\{1\}$$$;  $$$\{1, 3\}$$$;  $$$\{3\}$$$;  $$$\{3, 4, 5, 6, 7\}$$$;  $$$\{5\}$$$;  $$$\{8\}$$$. We will get the graph:There are no rainbow cycles in it.

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

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

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

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

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

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

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

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [m, n] = $(2), a = $(m), b = $(n), s
  let Am = Arr(m, i => (s = $(), $(s)))
  let edge = Am.map((A, i) => A.map(v => ({ x: i, y: m + v - 1, c: a[i] + b[v - 1] }))).flat();

  let par = Array(m + n).fill(-1);
  let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
  let dsu = (x, y) => {
    if ((x = root(x)) == (y = root(y))) return;
    if (par[y] < par[x]) [x, y] = [y, x];
    par[x] += par[y];
    par[y] = x;
    return true;
  }

  let maxSpan = 0;
  edge.sort((e1, e2) => e2.c - e1.c).forEach(e => {
    if (dsu(e.x, e.y)) maxSpan += e.c;
  });
  log(edge.sum(e => e.c) - maxSpan)
}


You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way.   Initially, you place block $$$1$$$ at $$$(0, 0)$$$.  For $$$2 \le i \le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently:   Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers. The $$$r$$$-th of them should be the maximum size of an tower of color $$$r$$$ you can form by following the given rules. If you cannot form any tower of color $$$r$$$, the $$$r$$$-th integer should be $$$0$$$.

NoteIn the first test case, one of the possible ways to form a tower of color $$$1$$$ and size $$$3$$$ is:   place block $$$1$$$ at position $$$(0, 0)$$$;  place block $$$2$$$ to the right of block $$$1$$$, at position $$$(1, 0)$$$;  place block $$$3$$$ above block $$$2$$$, at position $$$(1, 1)$$$;  place block $$$4$$$ to the left of block $$$3$$$, at position $$$(0, 1)$$$;  place block $$$5$$$ to the left of block $$$4$$$, at position $$$(-1, 1)$$$;  place block $$$6$$$ above block $$$5$$$, at position $$$(-1, 2)$$$;  place block $$$7$$$ to the right of block $$$6$$$, at position $$$(0, 2)$$$.   The blocks at positions $$$(0, 0)$$$, $$$(0, 1)$$$, and $$$(0, 2)$$$ all have color $$$1$$$, forming an tower of size $$$3$$$.In the second test case, note that the following placement is not valid, since you are not allowed to place block $$$6$$$ under block $$$5$$$:  It can be shown that it is impossible to form a tower of color $$$4$$$ and size $$$3$$$.

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = parseInt(readLine(), 10);
    for(let i = 0; i < t; i++){
        const n = +readLine();
        const arr = readLine().split(' ').map(p => +p);
        myFunc(n, arr);
    }
}

function myFunc(n, arr){
    let resp = new Array(n).fill(0);
    let last = new Array(n);

    for(let j = 0; j < n; j++){
        if(last[arr[j]-1] == undefined){
            last[arr[j]-1] = j;
            resp[arr[j]-1]++;
        }
    }

    for(let i = 1; i < n; i++){
        if( (i-1-last[arr[i]-1])%2 == 0 ){
            resp[arr[i]-1]++;
        }
        last[arr[i]-1] = i;
    }//for1

    console.log(resp.join(' '));

}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let res = new Array(n).fill(0);
    let obj = {};
    for (let i = 0; i < n; i++) {
      if (obj[arr[i]]) obj[arr[i]].push(i);
      else {
        let k = [i];
        obj[arr[i]] = k;
      }
      res[arr[i] - 1] = 1;
    }
    for (let i of Object.keys(obj)) {
      let k = obj[i];
      if (k.length > 1) {
        for (let j = 0; j < k.length - 1; j++) {
          if ((k[j + 1] - k[j]) % 2 === 1) res[i - 1] += 1;
        }
      }
    }
    console.log(res.join(" "));
  }
};
solve();

'use strict';

function solve(n, a) {
  const cnt = Array.from({
    length: n
  }, () => []);
  for (let [i, num] of a.entries()) {
    cnt[num - 1].push(i);
  }
  const res = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    let t = -1,
        ans = 0,
        p = cnt[i][0] & 1 ^ 1;
    for (let j = 0; j < cnt[i].length; j++) {
      const num = cnt[i][j];
      if ((num & 1) !== p) {
        p ^= 1;
        ans++;
      } else if (t === -1) {
        t = j;
      }
    }
    if (t !== -1) {
      p = cnt[i][t] & 1 ^ 1;
      let ans1 = 0;
      for (let j = t; j < cnt[i].length; j++) {
        const num = cnt[i][j];
        if ((num & 1) !== p) {
          p ^= 1;
          ans1++;
        }
      }
      ans = Math.max(ans, ans1);
    }
    res[i] = ans;
  }
  return res.join(' ');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


You are given two even integers $$$n$$$ and $$$m$$$. Your task is to find any binary matrix $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns where every cell $$$(i,j)$$$ has exactly two neighbours with a different value than $$$a_{i,j}$$$.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $$$(x,y)$$$ are: $$$(x-1,y)$$$, $$$(x,y+1)$$$, $$$(x+1,y)$$$ and $$$(x,y-1)$$$.It can be proven that under the given constraints, an answer always exists.

Each test contains multiple test cases. The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains two even integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 50$$$) — the height and width of the binary matrix, respectively.

For each test case, print $$$n$$$ lines, each of which contains $$$m$$$ numbers, equal to $$$0$$$ or $$$1$$$ — any binary matrix which satisfies the constraints described in the statement. It can be proven that under the given constraints, an answer always exists.

NoteWhite means $$$0$$$, black means $$$1$$$. The binary matrix from the first test caseThe binary matrix from the second test caseThe binary matrix from the third test case

'use strict';

function solve(n, m) {
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[0][i] = res[0][i - 1] ^ 1;
    } else {
      res[0][i] = res[0][i - 1];
    }
  }
  res[1][0] = 1;
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[1][i] = res[1][i - 1] ^ 1;
    } else {
      res[1][i] = res[1][i - 1];
    }
  }
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const nums = [];
    for (let i = 0; i < parseInt(n / 4); i++) nums.push(1, 0, 0, 1);
    if (n % 4 >= 1) nums.push(1);
    if (n % 4 >= 2) nums.push(0);
    if (n % 4 >= 3) nums.push(0);

    const numsInv = [];
    for (let i = 0; i < n; i++) numsInv.push((nums[i] + 1) % 2);

    const matrix = [];
    for (let i = 0; i < parseInt(m / 4); i++) {
      matrix.push([...nums]);
      matrix.push([...numsInv]);
      matrix.push([...numsInv]);
      matrix.push([...nums]);
    }

    if (m % 4 >= 1) matrix.push([...nums]);
    if (m % 4 >= 2) matrix.push([...numsInv]);
    if (m % 4 >= 3) matrix.push([...numsInv]);

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        const [rows, cols] = readline().split(' ').map(Number);

        for (let row = 0; row < rows; row++) {
            let line = '';
            for (let col = 0; col < cols; col++) {
                if (col !== 0) {
                    line += ' ';
                }
            if (row % 4 === 0 || row % 4 === 3) {
                line += (col % 4 === 0 || col % 4 === 3) ? '0' : '1';
            } else {
                line += (col % 4 === 0 || col % 4 === 3) ? '1' : '0';
            }
            }
            output(line);
          }
    }
}

'use strict';

function solve(n, m) {
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[0][i] = res[0][i - 1] ^ 1;
    } else {
      res[0][i] = res[0][i - 1];
    }
  }
  res[1][0] = 1;
  for (let i = 1; i < m; i++) {
    if ((i ^ 1) === i - 1) {
      res[0][i] = res[0][i - 1] ^ 1;
    } else {
      res[0][i] = res[0][i - 1];
    }
  }
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m) {
  if (n === 2 && m === 2) return `0 1\n1 0`;
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 2; i < m; i += 4) {
    res[0][i] = res[0][i - 1] = 1;
  }
  res[1][0] = 1;
  res[1][m - 1] = 1;
  for (let i = 4; i < m; i += 4) res[1][i] = res[1][i - 1] = 1;
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, m) {
  if (n === 2 && m === 2) return `0 0\n0 0`;
  const res = Array.from({
    length: n
  }, () => new Array(m).fill(0));
  for (let i = 2; i < m; i += 4) {
    res[0][i] = res[0][i - 1] = 1;
  }
  res[1][0] = 1;
  res[1][m - 1] = 1;
  for (let i = 4; i < m; i += 4) res[1][i] = res[1][i - 1] = 1;
  for (let i = 2; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if ((i ^ 1) === i - 1) {
        res[i][j] = res[i - 1][j] ^ 1;
      } else {
        res[i][j] = res[i - 1][j];
      }
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      res[i] = solve(n, m);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const nums = [];
    for (let i = 0; i < parseInt(n / 4); i++) nums.push(1, 0, 0, 1);
    if (n % 4 >= 1) nums.push(1);
    if (n % 4 >= 2) nums.push(0);
    if (n % 4 >= 3) nums.push(0);

    const numsInv = [];
    for (let i = 0; i < n; i++) numsInv.push((nums[i] + 1) % 2);

    const matrix = [];
    for (let i = 0; i < parseInt(m / 4); i++) {
      matrix.push([...nums]);
      matrix.push([...numsInv]);
      matrix.push([...numsInv]);
      matrix.push([...nums]);
    }

    if (n % 4 >= 1) matrix.push([...nums]);
    if (n % 4 >= 2) matrix.push([...numsInv]);
    if (n % 4 >= 3) matrix.push([...numsInv]);

    // for (let i = 0; i < m; i++) matrix.push([...nums]);
    // for (let i = 1; i < m; i += 2) {
    //   for (let j = 0; j < n; j++) {
    //     matrix[i][j] = (matrix[i][j] + 1) % 2;
    //   }
    // }

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const nums = [];
    for (let i = 0; i < parseInt(n / 4); i++) nums.push(1, 0, 0, 1);
    if (n % 4 >= 1) nums.push(1);
    if (n % 4 >= 2) nums.push(0);
    if (n % 4 >= 3) nums.push(0);

    const matrix = [];
    for (let i = 0; i < m; i++) matrix.push([...nums]);
    for (let i = 1; i < m; i += 2) {
      for (let j = 0; j < n; j++) {
        matrix[i][j] = (matrix[i][j] + 1) % 2;
      }
    }

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var arr = "";
process.stdin.on("data", function (chunk) {
  arr += chunk;
});

process.stdin.on("end", function () {
  arr = arr.split("\n");
  const testcases = parseInt(arr.shift());
  for (let t = 0; t < testcases; t++) {
    const [m, n] = arr[t].split(" ").map((el) => parseInt(el));

    const matrix = [];
    for (let i = 0; i < m; i++) matrix.push([]);

    for (let i = 0; i < m; i += 2) {
      let start = 0;
      for (let j = 0; j < n; j++) {
        matrix[i][j] = (start + 1) % 2;
        start = (start + 1) % 2;
      }
    }

    for (let i = 1; i < m; i += 2) {
      let start = 1;
      for (let j = 0; j < n; j++) {
        matrix[i][j] = (start + 1) % 2;
        start = (start + 1) % 2;
      }
    }

    console.log(matrix.map((el) => el.join(" ")).join("\n"));
  }
});