You are given a string $$$s$$$ consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string $$$s$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first and only line of each test case contains the string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) consisting of characters 0, 1, and ?. It is guaranteed that the sum of the string lengths over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of beautiful substrings of the string $$$s$$$.

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 () {
	let T = rn();
	while (T--) {
		const s = rl().split('');
		const n = s.length;

		const px = Array(n).fill(0); px[-1] = 0;
		for (let i = 0; i < n; i++) if (s[i] == '?') px[i] = px[i-1] + 1;

		let ans = 0;
		for (let i = 0, cnt = 0; i < n; i++) {

			if (s[i] == '?') s[i] = 1 ^ s[i-1];

			if (s[i] == s[i-1]) cnt = 1 + px[i-1];
			else cnt++;

			ans += cnt;
		}

		console.log(ans);
	}
}

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 () {
	let T = rn();
	while (T--) {
		const S = rl().split('');
		const n = S.length;

		for (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;
		const px = Array(n).fill(0); px[-1] = 0;
		for (let i = 0; i < n; i++) if (S[i] == '?') px[i] = px[i-1] + 1;

		s = S.slice();
		if (s[0] == '?') s[0] = 0;

		let ans = 0;

		let res = 1, cnt = 1;
		for (let j = 1; j < n; j++) {
			if (s[j] == '?') s[j] = 1 ^ s[j-1];
			if (s[j] == s[j-1]) {
				cnt = 1 + px[j-1];
			} else {
				cnt++;
			}
			res += cnt;
		}
		ans = Math.max(ans, res);

		console.log(ans);
	}
}

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 () {
	let T = rn();
	while (T--) {
		const S = rl().split('');
		const n = S.length;

		for (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;

		let ans = 0;
		for (let i = 0; i < 2; i++) {
			s = S.slice();
			if (s[0] == '?') s[0] = i;

			let res = 1, cnt = 1;
			for (let j = 1; j < n; j++) {
				if (s[j] == '?') s[j] = 1 ^ s[j-1];
				if (s[j] == s[j-1]) {
					cnt = 1;
					k = j-1;
					while (k >= 0 && S[k] == '?') { cnt++; k--;}
				} else {
					cnt++;
				}
				res += cnt;
			}

			ans = Math.max(ans, res);
		}

		console.log(ans);
	}
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function solve() {
   var str = read();
   var mark = [];
   var n = str.length;
   var curStreak = -1;
   var lastIndex = -1n;
   var lastDigitIndex = -1n;
   var questionStreak = 0n;
   var ans = 0n;
   for (var i = 0; i < n; i++) {
      var char = str[i];
      if (char === '?') {
         questionStreak += 1n;
         continue;
      }
      var x = (char === '1') ? !(i & 1) : !!(i & 1);
      if (curStreak === -1) {
         curStreak = x;
      }
      var bigi = BigInt(i);
      if (curStreak === x) {
         lastDigitIndex = bigi;
         questionStreak = 0n;
         continue;
      }
      curStreak = x;
      var len = bigi - 1n - lastIndex;
      ans = ans + (len * (len + 1n) / 2n) - (questionStreak * (questionStreak + 1n) / 2n);
      lastIndex = lastDigitIndex;
      lastDigitIndex = bigi;
      questionStreak = 0n;
   }
   var len = BigInt(n - 1) - lastIndex;
   ans = ans + (len * (len + 1n) / 2n);
   write(ans);
}

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

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

///////////////////////////////// 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; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 06/04/21 morning
 * https://codeforces.com/contest/1535/problem/C
 */

const solve = (s) => {
    let n = s.length;
    let pos = Array(n).fill(-1);
    for (let i = 0; i < n; i++) {
        if (s[i] != '?') pos[i] = s[i] ^ (i % 2);
    }
    let zero = one = res = 0;
    // pr(pos);
    let j = -1; // right
    for (let i = 0; i < n; i++) {
        while (j < n && (zero == 0 || one == 0)) {
            j++;
            if (pos[j] == 0) {
                zero++;
            } else if (pos[j] == 1) {
                one++;
            }
        }
        res += j - i;
        if (pos[i] == 0) {
            zero--;
        } else if (pos[i] == 1) {
            one--;
        }
    }
    pr(res);
};

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);
    });
    rl.on('close', () => {
        let t = Number(input[0]);
        let i = 1;
        while (t--) {
            solve(input[i]);
            i++;
        }
    });
};

main()

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var str = lines[l++]
        console.log(solve(str));
    }
});

function solve(str) {
    let sum = 0
    let expect = '?'
    let prev = 0
    for (let i = 0; i < str.length; i++) {
        const ch = str[i]
        if (isMatch(expect, ch)) {
            prev++

            if (expect === '?') {
                if (ch !== '?') expect = getOther(ch)
            } else {
                expect = getOther(expect)
            }
        } else {
            let j = i
            while (j >= 0) {
                const change = (i - j) & 1
                const other = getOther(str[j])
                if (str[j] !== '?'
                    && !isMatch(ch, change ? other : str[j])) {
                    j++
                    break
                }
                j--
            }
            prev = i - j + 1
            expect = getOther(ch)
        }

// console.log(prev)
        sum += prev
    }
// console.log('----')
    return sum
}

function isMatch(expect, actual) {
    if (expect === '?' || actual === '?') return true
    return expect === actual
}
function getOther(ch) {
    return ch === '0' ? '1' : '0'
}

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 () {
	let T = rn();
	while (T--) {
		const S = rl().split('');
		const n = S.length;

		for (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;
		const px = Array(n).fill(0); px[-1] = 0;
		for (let i = 0; i < n; i++) if (S[i] == '?') px[i] = px[i-1] + 1;

		s = S.slice();
		if (s[0] == '?') s[0] = 0;

		let ans = 0;

		let res = 1, cnt = 1;
		for (let j = 1; j < n; j++) {
			if (s[j] == '?') s[j] = 1 ^ s[j-1];
			if (s[j] == s[j-1]) {
				cnt = 1 + px[j-1];
			} else {
				cnt++;
			}
			res += cnt;

			ans = Math.max(ans, res);
		}

		console.log(ans);
	}
}

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 () {
	let T = rn();
	while (T--) {
		const S = rl().split('');
		const n = S.length;

		for (let i = 0; i < n; i++) if (S[i] != '?') S[i] = S[i] - 0;

		let ans = 0;
		for (let i = 0; i < 2; i++) {
			s = S.slice();
			if (s[0] == '?') s[0] = i;
			//else s[0] = s[0]-0;

			let res = 1, cnt = 1;
			for (let j = 1; j < n; j++) {
				if (s[j] == '?') s[j] = 1 ^ s[j-1];
				if (s[j] == s[j-1]) {
					cnt = 1;
					k = j-1;
					while (k >= 0 && S[k] == '?') { cnt++; k++;}
				} else {
					cnt++;
				}
				res += cnt;
			}

			ans = Math.max(ans, res);
		}

		console.log(ans);
	}
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function solve() {
   var str = read();
   var mark = [];
   var n = str.length;
   var curStreak = -1;
   var lastIndex = -1n;
   var lastDigitIndex = -1n;
   var questionStreak = 0n;
   var ans = 0n;
   for (var i = 0; i < n; i++) {
      var char = str[i];
      if (char === '?') {
         questionStreak += 1n;
         continue;
      }
      var x = (char === '1') ? !(i & 1) : !!(i & 1);
      if (curStreak === -1) {
         curStreak = x;
      }
      var bigi = BigInt(i);
      if (curStreak === x) {
         lastDigitIndex = bigi;
         questionStreak = 0n;
         continue;
      }
      curStreak = x;
      var len = bigi - 1n - lastIndex;
      ans = ans + (len * (len + 1n) / 2n) - (questionStreak * (questionStreak + 1n) / 2n);
      lastIndex = lastDigitIndex;
   }
   var len = BigInt(n - 1) - lastIndex;
   ans = ans + (len * (len + 1n) / 2n);
   write(ans);
}

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

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function solve() {
   var str = read();
   var mark = [];
   var n = str.length;
   var curStreak = -1;
   var lastIndex = -1n;
   var lastDigitIndex = -1n;
   var ans = BigInt(n);
   for (var i = 0; i < n; i++) {
      var char = str[i];
      if (char === '?') {
         continue;
      }
      var x = (char === '1') ? !(i & 1) : !!(i & 1);
      if (curStreak === -1) {
         curStreak = x;
      }
      var bigi = BigInt(i);
      if (curStreak === x) {
         lastDigitIndex = bigi;
         continue;
      }
      curStreak = x;
      var len = bigi - 1n - lastIndex;
      ans = ans + (len * (len - 1n) / 2n);
      lastIndex = lastDigitIndex;
      lastDigitIndex = bigi;
   }
   var len = BigInt(n - 1) - lastIndex;
   ans = ans + (len * (len - 1n) / 2n);
   write(ans);
}

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

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function solve() {
   var str = read();
   var mark = [];
   var n = str.length;
   var curStreak = -1;
   var lastIndex = -1n;
   var lastDigitIndex = -1n;
   var ans = BigInt(n);
   for (var i = 0; i < n; i++) {
      var char = str[i];
      if (char === '?') {
         continue;
      }
      var x = (char === '1') ? !(i & 1) : !!(i & 1);
      if (curStreak === -1) {
         curStreak = x;
      }
      var bigi = BigInt(i);
      if (curStreak === x) {
         lastDigitIndex = bigi;
         continue;
      }
      curStreak = x;
      var len = bigi - 1n - lastIndex;
      ans = ans + (len * (len - 1n) / 2n);
      lastIndex = lastDigitIndex;
   }
   var len = BigInt(n - 1) - lastIndex;
   ans = ans + (len * (len - 1n) / 2n);
   write(ans);
}

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

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}


Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.

The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.

If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.

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

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

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

function main() {
	var vertexNum = parseInt(readline());

	var edges = {
		augment: function(u, v) {
			if (edges[u] === undefined) {
				edges[u] = [v];
			}
			else {
				edges[u].push(v);
			}
		}
	};

	for (var i = 1; i < vertexNum; ++i) {
		var pair = tokenizeIntegers(readline());
		edges.augment(pair[0], pair[1]);
		edges.augment(pair[1], pair[0]);
	}

	var nodes = {};
	var root = 1;

	function descend(path) {
		var current = path[path.length-1];
		nodes[current] = { index: current,
				children: [],
				leaves: [], hasLeaf: {}, leafCount: 0,
				parent: path[path.length-2], visitCount: 0 };

		var neighbors = edges[current];
		if (neighbors.length == 1 && current != root) {
			nodes[current].isLeaf = true;
			for (var i = path.length-1; i >= 0; --i) {
				var node = nodes[path[i]];
				node.leaves.push(current);
				node.hasLeaf[current] = true;
				node.leafCount += 1;
			}
			return;
		}

		for (var i = 0; i < neighbors.length; ++i) {
			var child = neighbors[i];
			if (path.length > 1 && path[path.length-2] == child) {
				continue;
			}

			nodes[current].children.push(child);

			path.push(child);
			descend(path);
			path.pop();
		}
	}

	descend([root]);

	var order = tokenizeIntegers(readline());

	var seek = root,
		route = [root],
		node = nodes[root];
	node.visitCount = 1;

	for (var i = 0; i < order.length; ++i) {
		var target = order[i];
		while (!node.hasLeaf[target]) {  // ascend
			seek = node.parent;
			route.push(seek);
			node = nodes[seek];
			node.visitCount += 1;
			if (node.visitCount > 1+node.children.length) {
				print(-1);
				return;
			}
		}
		while (seek != target) {  // descend
			for (var j = 0; j < node.children.length; ++j) {
				if (nodes[node.children[j]].hasLeaf[target]) {
					seek = node.children[j];
					break;
				}
			}
			route.push(seek);
			node = nodes[seek];
			node.visitCount += 1;
		}
	}

	while (seek != root) {
		seek = node.parent;
		route.push(seek);
		node = nodes[seek];
		node.visitCount += 1;
		if (node.visitCount != 1+node.children.length) {
			print(-1);
			return;
		}
	}

	print(route.join(" "));
}

main();

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

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

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

function main() {
	var vertexNum = parseInt(readline());

	var edges = {
		augment: function(u, v) {
			if (edges[u] === undefined) {
				edges[u] = [v];
			}
			else {
				edges[u].push(v);
			}
		}
	};

	for (var i = 1; i < vertexNum; ++i) {
		var pair = tokenizeIntegers(readline());
		edges.augment(pair[0], pair[1]);
		edges.augment(pair[1], pair[0]);
	}

	var nodes = {};
	var root = 1;

	function descend(path) {
		var current = path[path.length-1];
		nodes[current] = {
				children: [],
				leadsToLeaf: {},
				parent: path[path.length-2], visitCount: 0
		};

		var neighbors = edges[current];
		if (neighbors.length == 1 && current != root) {  // it's a leaf
			for (var i = path.length-1; i >= 0; --i) {
				var node = nodes[path[i]];
				node.leadsToLeaf[current] = true;
			}
			return;
		}

		for (var i = 0; i < neighbors.length; ++i) {
			var child = neighbors[i];
			if (path.length > 1 && path[path.length-2] == child) {
				continue;  // don't descend to the parent
			}

			nodes[current].children.push(child);

			path.push(child);
			descend(path);
			path.pop();
		}
	}

	descend([root]);

	var order = tokenizeIntegers(readline());

	var seek = root,
		route = [root],
		node = nodes[root];
	node.visitCount = 1;

	for (var i = 0; i < order.length; ++i) {
		var target = order[i];
		while (!node.leadsToLeaf[target]) {  // ascend
			seek = node.parent;
			route.push(seek);
			node = nodes[seek];
			node.visitCount += 1;
			if (node.visitCount > 1+node.children.length) {
				print(-1);
				return;
			}
		}
		while (seek != target) {  // descend
			for (var j = 0; j < node.children.length; ++j) {
				if (nodes[node.children[j]].leadsToLeaf[target]) {
					seek = node.children[j];
					break;
				}
			}
			route.push(seek);
			node = nodes[seek];
			node.visitCount += 1;
		}
	}

	while (seek != root) {  // ascend to the root one last time
		seek = node.parent;
		route.push(seek);
		node = nodes[seek];
		node.visitCount += 1;
		if (node.visitCount != 1+node.children.length) {
			print(-1);
			return;
		}
	}

	print(route.join(" "));
}

main();

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

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

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

function main() {
	var vertexNum = parseInt(readline());

	var edges = {
		augment: function(u, v) {
			if (edges[u] === undefined) {
				edges[u] = [v];
			}
			else {
				edges[u].push(v);
			}
		}
	};

	for (var i = 1; i < vertexNum; ++i) {
		var pair = tokenizeIntegers(readline());
		edges.augment(pair[0], pair[1]);
		edges.augment(pair[1], pair[0]);
	}

	var nodes = {};
	var root = 1;

	function descend(path) {
		var current = path[path.length-1];
		nodes[current] = { index: current,
				children: [],
				leaves: [], hasLeaf: {}, leafCount: 0,
				parent: path[path.length-2], visitCount: 0 };

		var neighbors = edges[current];
		if (neighbors.length == 1 && current != root) {
			nodes[current].isLeaf = true;
			for (var i = path.length-1; i >= 0; --i) {
				var node = nodes[path[i]];
				node.leaves.push(current);
				node.hasLeaf[current] = true;
				node.leafCount += 1;
			}
			return;
		}

		for (var i = 0; i < neighbors.length; ++i) {
			var child = neighbors[i];
			if (path.length > 1 && path[path.length-2] == child) {
				continue;
			}

			nodes[current].children.push(child);

			path.push(child);
			descend(path);
			path.pop();
		}
	}

	descend([root]);

	var order = tokenizeIntegers(readline());

	var seek = root,
		route = [root],
		node = nodes[root];

	for (var i = 0; i < order.length; ++i) {
		var target = order[i];
		while (!node.hasLeaf[target]) {  // ascend
			seek = node.parent;
			route.push(seek);
			node = nodes[seek];
			node.visitCount += 1;
			if (node.visitCount > 2*node.children.length) {
				print(-1);
				return;
			}
		}
		while (seek != target) {  // descend
			for (var i = 0; i < node.children.length; ++i) {
				if (nodes[node.children[i]].hasLeaf[target]) {
					seek = node.children[i];
					break;
				}
			}
			route.push(seek);
			node = nodes[seek];
			node.visitCount += 1;
		}
	}

	while (true) {
		seek = node.parent;
		route.push(seek);
		node = nodes[seek];
		node.visitCount += 1;
		if (seek == root) {
			print(route.join(" "));
			return;
		}
		if (node.visitCount != 2*node.children.length) {
			print(-1);
			return;
		}
	}
}

main();


Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.  There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.  Masculine adjectives end with -lios, and feminine adjectives end with -liala.  Masculine nouns end with -etr, and feminime nouns end with -etra.  Masculine verbs end with -initis, and feminime verbs end with -inites.  Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.  It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.  There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.  A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.  All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.

The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.

If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).

petr
etis atis animatis etis atis amatis
nataliala kataliala vetra feinites

var str = readline();
var arr = str.split(' ');
var adj_fem = function(str) {return (str.substr(-5, 5) === 'liala')};
var adj_mal = function(str) {return (str.substr(-4, 4) === 'lios')};
var noun_fem = function(str) {return (str.substr(-4, 4) === 'etra')};
var noun_mal = function(str) {return (str.substr(-3, 3) === 'etr')};
var verb_fem = function(str) {return (str.substr(-6, 6) === 'inites')};
var verb_mal = function(str) {return (str.substr(-6, 6) === 'initis')};
var checks = [adj_fem, adj_mal, noun_fem, noun_mal, verb_fem, verb_mal];
var result = 0;
var i;
if (arr.length === 1) {
    i = -1;
    while (++i < checks.length)
        result |= checks[i](arr[0]);
} else {
    i = 0;
    result = 1;
    while ((i < arr.length) && (result &= (checks[0](arr[i]) || checks[1](arr[i])))) i++;
    result = 1;
    result &= ((i < arr.length) && (checks[2](arr[i]) || checks[3](arr[i])));
    i++;
    while ((i < arr.length) && (result &= (checks[4](arr[i]) || checks[5](arr[i])))) i++;

    i = 0;
    test2 = true, test3 = true;
    while ((i < arr.length) && (test2 &= (checks[0](arr[i]) || checks[2](arr[i]) || checks[4](arr[i])))) i++;
    i = 0;
    while ((i < arr.length) && (test3 &= (checks[1](arr[i]) || checks[3](arr[i]) || checks[5](arr[i])))) i++;
    result = (result & test2) || (result & test3);
}
write(result ? 'YES' : 'NO')


Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) — the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) — the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.

NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.

const solve = (ch,cd,mh,md,k,w,a)=>{
     let chelath = Math.ceil(ch/md);
     let cdamage = Math.ceil(mh/cd);
     if(cdamage<=chelath) console.log("YES");
     else if(k===0) console.log("NO");
     else{
          cd = cd + (k*w);
          for(let i=0;i<=k;i++){
               if(i!=0){
                    cd-=w;
                    ch+=a;
               }
               chelath = Math.ceil(ch/md);
               cdamage = Math.ceil(mh/cd);
               if(cdamage<=chelath){
                    console.log("YES");
                    return;
               }
          }
          console.log("NO");
     }
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let arr1 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr2 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr3 = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr1[0],arr1[1],arr2[0],arr2[1],arr3[0],arr3[1],arr3[2]);
  }
}
main();

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 [hc, dc] = lines[l++].trim().split(' ').map(Number)
        const [hm, dm] = lines[l++].trim().split(' ').map(Number)
        const [k, w, a] = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(hc, dc, hm, dm, k, w, a) ? 'YES' : 'NO'
    }
    console.log(output.join('\n'))
// })()
})

function solve(hc, dc, hm, dm, k, w, a) {
    for (let i = 0; i <= k; i++) {
        const j = k - i
        if (win(hc + i * a, dc + j * w, hm, dm)) return true
    }
    return false
}
function win(hc, dc, hm, dm) {
    const a = Math.ceil(hc / dm)
    const b = Math.ceil(hm / dc)
    return a >= b
}

const check = (hc,dc,hm,dm) =>{
    return (Math.ceil(hc/dm)>=Math.ceil(hm/dc));
}
var t=readline();
while(t--){
    var h=readline().split(" ").map(x => parseInt(x));
    var m=readline().split(" ").map(x => parseInt(x));
    var att=readline().split(" ").map(x => parseInt(x));
    var pos=0;
    var l,r;
    for(var i=0;i<=att[0];i++){
        l=i;
        r=att[0]-i;
        pos|=check(h[0]+att[2]*l,h[1]+att[1]*r,m[0],m[1]);
    }

    if(pos>0){
        print("YES");
    }else print("NO");
}

function check(hc,dc,hm,dm){
    return (Math.ceil(hc/dm)>=Math.ceil(hm/dc));
}
var t=readline();
while(t--){
    var h=readline().split(" ").map(x => parseInt(x));
    var m=readline().split(" ").map(x => parseInt(x));
    var att=readline().split(" ").map(x => parseInt(x));
    var pos=0;
    var l,r;
    for(var i=0;i<=att[0];i++){
        l=i;
        r=att[0]-i;
        pos|=check(h[0]+att[2]*l,h[1]+att[1]*r,m[0],m[1]);
    }

    if(pos>0){
        print("YES");
    }else print("NO");
}

var lines = parseInt(readline());

for (var i = 0; i < lines; i++) {
  var line = readline().split(" ");
  var hpC = parseInt(line[0]);
  var damC = parseInt(line[1]);
  line = readline().split(" ");
  var hpE = parseInt(line[0]);
  var damE = parseInt(line[1]);
  line = readline().split(" ");
  var coins = parseInt(line[0]);
  var attack = parseInt(line[1]);
  var defense = parseInt(line[2]);
  var h = 0;
  var win = false;
  while (!win && h <= coins) {
    var turnsC = Math.ceil(hpE / (damC + attack * h));
    var turnsE = Math.ceil((hpC + defense * (coins - h)) / damE);
    if (turnsC <= turnsE) {
      win = true;
      print("YES");
    } else {
      var hForSpeedUp = Math.ceil((hpE / (turnsC - 1) - damC) / attack);
      var hForSlowDown = Math.ceil(((turnsE + 1) * damE - hpC) / defense);
      h += Math.min(hForSpeedUp - h, hForSlowDown - (coins - h));
    }
  }
  if (!win) print("NO");
}

const solve = (ch,cd,mh,md,k,w,a)=>{
     let chelath = Math.floor(ch/md)+1;
     let cdamage = Math.ceil(mh/cd);
     if(cdamage<=chelath) console.log("YES");
     else if(k===0) console.log("NO");
     else{
          cd = cd + (k*w);
          for(let i=0;i<=k;i++){
               if(i!=0){
                    cd-=w;
                    ch+=a;
               }
               chelath = Math.floor(ch/md)+1;
               cdamage = Math.ceil(mh/cd);
               if(cdamage<=chelath){
                    console.log("YES");
                    return;
               }
          }
          console.log("NO");
     }
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let arr1 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr2 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr3 = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr1[0],arr1[1],arr2[0],arr2[1],arr3[0],arr3[1],arr3[2]);
  }
}
main();


Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.

The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.

If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).

NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.

  var tmp = readline().split(' ').map(function(x) { return parseInt(x)});
  var n = tmp[0];
  var m = tmp[1];
  var e = [];
  var vis = [];
  for(var i = 1; i <= n; i += 1) {
    e[i] = [];
    vis[i] = false;
  }
  for(var i = 1; i <= m; i += 1) {
    var tmp = readline().split(' ').map(function(x) { return parseInt(x)});
    e[tmp[0]].push(tmp[1]);
    e[tmp[1]].push(tmp[0]);
  }
  var finding = true;
  for(var i = 1; i <= n && finding; i += 1) {
    if(!vis[i]) {
      vis[i] = true;
      var vn = 1;
      var en = e[i].length;
      var stack = [i];
      while(stack.length > 0) {
        var d = stack.pop();
        for(var b in e[d]) {
          if(!vis[e[d][b]]) {
            vis[e[d][b]] = true;
            stack.push(e[d][b]);
            vn += 1;
            en += e[e[d][b]].length;
          }
        }
      }
      if(en !== vn * (vn - 1)) {
        finding = false;
      }
    }
  }
  if(finding) {
    print('YES');
  } else {
    print('NO');
  }

/*filesystem = require('fs');
var inputLines = filesystem.readFileSync('input.txt').toString().split('\n');
var inputIndex = 0;

function readline() {
    return inputLines[inputIndex++];
}

function print() {
    var ans = "";
    for (var i = 0; i < arguments.length; i++) {
        if (i != 0) ans += " ";
        ans += arguments[i].toString();
    }
    console.log(ans);
}*/
//FILESYSTEM

var currentLine;
var currentIndex;
function read() {
    if ((currentLine == null) || (currentIndex == currentLine.length)) {
        currentLine = readline().split(' ');
        currentIndex = 0;
    }
    return currentLine[currentIndex++];
}

function readInt() {
    return parseInt(read());
}
//HELPERS
function dfs(v) {
    var q = [];
    q.push(v);
    w[v] = true;
    for (var i = 0; i < q.length; i++) {
        var v = q[i];
        for (var j = 0; j < e[v].length; j++) {
            var u = e[v][j];
            if (!w[u]) {
                q.push(u);
                w[u] = true;
            }
        }
    }
    return q.length;
}

var n = readInt(), m = readInt();
var w = new Array(n + 1).fill(false);
var e = new Array(n + 1);
for (var i = 1; i <= n; i++) e[i] = [];
for (var i = 0; i < m; i++) {
    var a = readInt(), b = readInt();
    e[a].push(b);
    e[b].push(a);
}
var tot = 0;
for (var i = 1; i <= n; i++) {
    if (!w[i]) {
        var size = dfs(i);
        tot += size * (size - 1);
    }
}
if (tot == 2 * m) print('YES');
else print('NO');

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	links_count = [],
	links = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		links[i] = []
		links_count[i] = 0
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		links_count[pos[0]] ++
		links_count[pos[1]] ++
		if (pos[0] < pos[1])
			links[pos[0]].push(pos[1])
		else
			links[pos[1]].push(pos[0])
	}

	for (x = 1; x < n && !failed; x ++) {
		i = links[x].length - 1
		while (i >= 0 && !failed) {
			failed = links_count[x] != links_count[links[x][i]]
			links_count[links[x][i]] --
			i --
		}
	}

	if (failed)
		print("NO")
	else
		print("YES")
}

  var tmp = readline().split(' ').map(function(x) { return parseInt(x)});
  var n = tmp[0];
  var m = tmp[1];
  var e = [];
  var vis = [];
  for(var i = 1; i <= n; i += 1) {
    e[i] = [];
    vis[i] = false;
  }
  for(var i = 1; i <= m; i += 1) {
    var tmp = readline().split(' ').map(function(x) { return parseInt(x)});
    e[tmp[0]].push(tmp[1]);
    e[tmp[1]].push(tmp[0]);
  }
  var cnt_vertices = 0
  var cnt_edges = 0;
  var stack = [];
  var dfs = function(x) {
    stack.push(x);
    while(stack.length > 0) {
      var a = stack.pop();
      if(vis[a]) {
        continue;
      }
      vis[a] = true;
      vn += 1;
      en += e[a].length;
      for(var b in e[a]) {
        stack.push(e[a][b]);
        // dfs(e[a][b]);
      }
    }
  };
  var finding = true;
  var vn = 0;
  var en = 0;
  for(var i = 1; i <= n && finding; i += 1) {
    if(!vis[i]) {
      vn = 0
      en = 0;
      dfs(i);
      if(en !== vn * (vn - 1)) {
        finding = false;
      }
    }
  }
  if(finding) {
    print('YES');
  } else {
    print('NO');
  }

  var tmp = readline().split(' ').map(function(x) { return parseInt(x)});
  var n = tmp[0];
  var m = tmp[1];
  var e = [];
  var vis = [];
  for(var i = 1; i <= n; i += 1) {
    e[i] = [];
    vis[i] = false;
  }
  for(var i = 1; i <= m; i += 1) {
    var tmp = readline().split(' ').map(function(x) { return parseInt(x)});
    e[tmp[0]].push(tmp[1]);
    e[tmp[1]].push(tmp[0]);
  }
  var finding = true;
  for(var i = 1; i <= n && finding; i += 1) {
    if(!vis[i]) {
      vis[i] = true;
      var vn = 1;
      var en = e[i].length;
      var stack = [i];
      while(stack.length > 0) {
        var d = stack.pop();
        for(var b in e[d]) {
          if(!vis[e[d][b]]) {
            vis[e[d][b]] = true;
            stack.push(e[d][b]);
            vn += 1;
            en += e[d].length;
          }
        }
      }
      if(en !== vn * (vn - 1)) {
        finding = false;
      }
    }
  }
  if(finding) {
    print('YES');
  } else {
    print('NO');
  }

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	links_count = [],
	links = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		links[i] = []
		links_count[i] = 0
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		links_count[pos[0]] ++
		links_count[pos[1]] ++
		if (pos[0] < pos[1])
			links[pos[0]].push(pos[1])
		else
			links[pos[1]].push(pos[0])
	}

	for (x = 1; x < n && !failed; x ++) {
		i = links[x].length - 1
		while (i >= 0 && !failed) {
			failed = links_count[x] != links_count[links[x][i]]
			i --
		}
	}

	if (failed)
		print("NO")
	else
		print("YES")
}

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	mem = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	friend = function(x, y) {
		return x < y ? (mem[x][y] !== undefined) : (mem[y][x] !== undefined)
	},
	failed = false

for(i = 0; i <=n; i++) {
	mem[i] = {}
}

for(i = 0; i < m; i++) {
	pos = ints()
	if (pos[0] < pos[1]) {
		x = pos[0]
		y = pos[1]
	} else {
		x = pos[1]
		y = pos[0]
	}
	mem[x][y] = true
}

i = 1
while (i <= n && !failed) {
	for (x in mem[i]) {
		for(y in mem[x]) {
			if (! friend(i, y)) {
				failed = true
				break
			}
		}
		if (failed)
			break
	}
	i ++
}

if (failed)
	print("NO")
else
	print("YES")

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	mem = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	friend = function(x, y) {
		return x < y ? (mem[x][y] !== undefined) : (mem[y][x] !== undefined)
	},
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		mem[i] = {}
		mem[i][i] = true
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		if (pos[0] < pos[1]) {
			x = pos[0]
			y = pos[1]
		} else {
			x = pos[1]
			y = pos[0]
		}
		mem[x][y] = true
	}

	i = 1
	while (i <= n && !failed) {
		for (x in mem[i]) {
			for(y in mem[x]) {
				if (! friend(i, y)) {
					failed = true
					break
				}
			}
			if (failed)
				break
		}
		i ++
	}

	if (failed)
		print("NO")
	else
		print("YES")
}

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	mem = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		mem[i] = 0
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		mem[pos[0]] ++
		mem[pos[1]] ++
	}

	for (x = 1; x < n && !failed; x ++)
		for (y = x + 1; y <= n && !failed; y ++)
			failed = (mem[x] != mem[y])

	if (failed)
		print("NO")
	else
		print("YES")
}

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	mem = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	friend = function(x, y) {
		return mem[x][y]
	},
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		mem[i] = []
		for(x = 0; x <=n; x++)
			mem[i][x] = false
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		mem[pos[0]][pos[1]] = true
		mem[pos[1]][pos[0]] = true
	}

	for(i = 1; i <=n && !failed; i++) {
		for(x = 1; x <=n && !failed; x++) {
			for(y = 1; y <=n && !failed; y++) {
				failed = friend(i, x) && friend(x, y) && !friend(i, y)
			}
		}
	}

	if (failed)
		print("NO")
	else
		print("YES")
}

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	mem = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	friend = function(x, y) {
		return x == y || mem[x][y]
	},
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		mem[i] = []
		for(x = 0; x <=n; x++)
			mem[i][x] = false
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		mem[pos[0]][pos[1]] = true
	}

	for(i = 1; i <=n && !failed; i++) {
		for(x = 1; x <=n && !failed; x++) {
			for(y = 1; y <=n && !failed; y++) {
				failed = friend(i, x) && friend(x, y) && !friend(x, y)
			}
		}
	}

	if (failed)
		print("NO")
	else
		print("YES")
}

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

// The answer

var ns = ints(),
	n = ns[0],
	m = ns[1]
	mem = [],
	i = 0,
	x = 0,
	y = 0,
	pos = [],
	friend = function(x, y) {
		return x < y ? (mem[x][y] !== undefined) : (mem[y][x] !== undefined)
	},
	failed = false

if (m == 0) {
	print("YES")
} else {
	for(i = 0; i <=n; i++) {
		mem[i] = {}
	}

	for(i = 0; i < m; i++) {
		pos = ints()
		if (pos[0] < pos[1]) {
			x = pos[0]
			y = pos[1]
		} else {
			x = pos[1]
			y = pos[0]
		}
		mem[x][y] = true
	}

	i = 1
	while (i <= n && !failed) {
		for (x in mem[i]) {
			for(y in mem[x]) {
				if (! friend(i, y)) {
					failed = true
					break
				}
			}
			if (failed)
				break
		}
		i ++
	}

	if (failed)
		print("NO")
	else
		print("YES")
}


Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string $$$s$$$, you have to delete minimum number of characters from this string so that it becomes good.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

In the first line, print one integer $$$k$$$ ($$$0 \le k \le n$$$) — the minimum number of characters you have to delete from $$$s$$$ to make it good. In the second line, print the resulting string $$$s$$$. If it is empty, you may leave the second line blank, or not print it at all.

'use strict';

function main() {
  let n = parseInt(next());
  let s = next();
  let stack = [], i = 0, res = '';
  for(i = 0; i < n; i++) {
    if((!stack.length) || s[i] != stack[stack.length-1] || stack.length % 2 == 0) {
      stack.push(s[i]);
    }
  }
  if(stack.length%2) stack.pop();
  res = stack.join('');
  println(n-res.length+'\n'+res);
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

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

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});

'use strict';

function main() {
  let n = parseInt(next());
  let s = next();
  let i = 0;

  let res = '';
  let ereased = 0;
  for(i = 0; i < n; i++) {
    if(i == n-1 || s[i+1] !== s[i]) {
      res += s[i];
    } else {
      let j = i+1;
      while(j < n && s[j] === s[i]) {
        j++;
      }
      j--;
      if((i-ereased)%2 == 0) {
        res += s[i];
        ereased += j-i;
      } else {
        res += s[i]+''+s[i];
        ereased += j-i-1;
      }
      i = j;
    }
  }

  if(res.length%2) {
    println(n-res.length+1);
    println(res.substr(0, res.length-1));
  } else {
    println(n-res.length);
    println(res.substr(0, res.length));
  }
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

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

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});

'use strict';

function main() {
  let n = parseInt(next());
  let s = next(), res = '';
  let i = 0, j = 0, ereased = 0;
  for(i = 0; i < n; i++) {
    if(i == n-1 || s[i+1] !== s[i]) {
      res += s[i];
    } else {
      j = i+1;
      while(j < n && s[j] === s[i]) {
        j++;
      }
      j--;
      if((i-ereased)%2) {
        res += s[i]+s[i];
        ereased += j-i-1;
      } else {
        res += s[i];
        ereased += j-i;
      }
      i = j;
    }
  }

  println(n-res.length+res.length%2);
  println(res.substr(0, res.length-res.length%2));
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

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

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var n = read.number();
    var a = read.arr();
    var res = [a[0]];
    var length = 0;
    for(var i = 1; i < n; i++) {
        if(length % 2) {
            res.push(a[i]);
            length++;
        }
        else {
            if(res[length] !== a[i]) {
                res.push(a[i]);
                length++;
            }
        }
    }
    length += 1;
    if(length % 2) {
        length -=1;
        res.pop();
    }

    print(n - length);
    print(res.join(''));
}());

'use strict';

function main() {
  let n = parseInt(next());
  let s = next();
  let i = 0;

  let res = '';
  let ereased = 0;
  for(i = 0; i < n; i++) {
    if(i == n-1 || s[i+1] !== s[i]) {
      res += s[i];
    } else {
      let j = i+1;
      while(j < n && s[j] === s[i]) {
        j++;
      }
      j--;
      if((i-ereased)%2 == 0) {
        res += s[i];
        ereased += j-i;
      } else {
        res += s[i]+''+s[i];
        ereased += j-i-1;
      }
      i = j;
    }
  }

  if(res.length%2) {
    println(n-res.length+1);
    println(s.substr(0, res.length-1));
  } else {
    println(n-res.length);
    println(s.substr(0, res.length));
  }
}

//process.stdin.resume();
process.stdin.setEncoding('ascii');

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

// next: reads next value from input.
let inputCursor = 0;
let next = () => {
  return inputCursor < input.length ? input[inputCursor++] : '';
};

//print: print one or more space seperated values.
let print = (...data) => {
  for(let i = 0; i < data.length; i++) {
    process.stdout.write(data[i] + (i < data.length - 1 ? ' ' : ''));
  }
};

//println: print one or more space seperated values then a line feed.
let println = (...data) => {
  print(...data);
  print('\n');
};

//after the the input is read.
process.stdin.on('end', () => {
    input = input.trim().split(/[\s]+/);
    main();
});


You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 106) — the number of segments and the value of k. The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.

First line contains integer m — the smallest number of segments. Next m lines contain two integers aj, bj (aj ≤ bj) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.


Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.

Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.

NoteIn the second example the upper left square is (1,1) and the lower right is (3,2).

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))
let N = lll[0]
let M = lll[1]

let s = []
while (lll = readline()) {
  s.push(lll.split(' ').map(v => parseInt(v)))
}

let ab = s.pop()
let A = ab[0]
let B = ab[1]

let min = Infinity

for (let y = 0; y <= N - A; y++) {
  for (let x = 0; x <= M - B; x++) {
    let ts = 0
    d: for (let dy = 0; dy < A; dy++) {
      for (let dx = 0; dx < B; dx++) {
        if (s[y + dy][x + dx] == 1) ts++
        if (ts >= min) break d
      }
    }
    if (ts < min) min = ts
  }
}

for (let y = 0; y <= N - B; y++) {
  for (let x = 0; x <= M - A; x++) {
    let ts = 0
    d: for (let dy = 0; dy < B; dy++) {
      for (let dx = 0; dx < A; dx++) {
        if (s[y + dy][x + dx] == 1) ts++
        if (ts >= min) break d
      }
    }
    if (ts < min) min = ts
  }
}

print(min)

const readline = require('readline');

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

var calculateTrees = function (cont, startRow, endRow, startCol, endCol) {
    let ans = 0;
    for (let i = startRow; i < endRow; i++)
        for (let j = startCol; j < endCol; j++)
            ans += cont[i][j];

    //console.log(" startRow=%d  endRow=%d  startCol=%d  endCol=%d   ans=%d",startRow, endRow, startCol, endCol,ans);
    return ans;
}

var indicator = 0, N, M, temp, cont = [], HouseX, HouseY;
rl.on('line', (input) => {
    if (indicator == 0) {
        temp = input.split(" ").map(item => parseInt(item));
        N = temp[0];
        M = temp[1];
        indicator++;
    }
    else if (indicator <= N) {
        cont.push(input.split(" ").map(item => parseInt(item)));
        indicator++;
    }
    else {
        temp = input.split(" ").map(item => parseInt(item));
        HouseX = temp[0];
        HouseY = temp[1];
    }
}).on('close', () => {
    let ans = N * M, helper;
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < M; j++) {
            if (i + HouseX <= N && j + HouseY <= M) {
                helper = calculateTrees(cont, i, i + HouseX, j, j + HouseY);
                if (ans > helper)
                    ans = helper;
            }
            if (i + HouseY <= N && j + HouseX <= M) {
                helper = calculateTrees(cont, i, i + HouseY, j, j + HouseX);
                if (ans > helper)
                    ans = helper;
            }
        }
    }
    console.log(ans);
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var calculateTrees = (cont, startRow, endRow, startCloumn, endColumn) => {
    let ans = 0;
    for (let i = startRow; i < endRow; i++)
        for (let j = startCloumn; j < endColumn; j++)
            if (cont[i][j] == 1)
                ans += cont[i][j];
    return ans;
}
var N, M, cont = [], houseX, houseY, indicator = 0, temp = [];
rl.on('line', (input) => {
    if (indicator == 0) {
        temp = input.split(' ').map(item => parseInt(item));
        N = temp[0], M = temp[1];
        indicator++;
    } else if (indicator <= N) {
        cont.push(input.split(' ').map(item => parseInt(item)));
        indicator++;
    } else {
        temp = input.split(' ').map(item => parseInt(item));
        houseX = temp[0], houseY = temp[1];
    }
}).on("close", () => {
    let ans = N * M, helper;
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < M; j++) {
            if (i + houseX <= N && j + houseY <= M) {
                helper = calculateTrees(cont, i, i + houseX, j, j + houseY);
                if (ans > helper)
                    ans = helper;
            }
            if (i + houseY <= N && j + houseX <= M) {
                helper = calculateTrees(cont, i, i + houseY, j, j + houseX);
                if (ans > helper)
                    ans = helper;
            }
        }
    }
    console.log(ans);
});

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

var getTree = function(arr, x, y, a, b) {
	var res = 0;
	for (var i = 0; i < a; i++) {
		for (var j = 0; j < b; j++) {
			res += arr[x + i][y + j];
		}
	}
	return res;
};

var data = [];
var input;

input = getArr();
var m = input[0];
var n = input[1];
for (var k = 0; k < m; k++) {
	data.push(getArr());
}
input = getArr();
var a = input[0];
var b = input[1];

var min = getTree(data, 0, 0, a, b);
for (var i = 0; i < m - a + 1; i++) {
	for (var j = 0; j < n - b + 1; j++) {
		min = Math.min(min, getTree(data, i, j, a, b));
	}
}

print(min);


Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:  some dwarf in one of the chosen lines is located in the rightmost cell of his row;  some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.

The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).  Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".

In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.

print(function(n, m){
	var a=[];
	for(var i=0; i<n; i++){
		var s=readline();
		var G=s.indexOf('G');
		var S=s.indexOf('S');
		if(S<G){
			return -1;
		}else{
			a.push(S-G);
		}
	}
	a.sort(function(a,b){return a-b;});
	var ans=1;
	for(var i=1;i<n;i++){
		if(a[i]!==a[i-1]) ans++;
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var rowNum = integers[0], colNum = integers[1];
	var gapFound = {}, gaps = [];
	for (var r = 0; r < rowNum; ++r) {
		var line = trim(readline());
		var gap = line.indexOf('S') - line.indexOf('G');
		if (gap < 0) {
			print(-1);
			return;
		}
		if (!gapFound[gap]) {
			gapFound[gap] = true;
			gaps.push(gap);
		}
	}
	print(gaps.length);
}

main();

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

for (var i=0; i<n; i++) {
	var s = readline();
	mas[i] = s.indexOf('S') - s.indexOf('G');
	if (mas[i] < 0) {
		print(-1);
		var ans = -1;
		break;
	}
}

if (ans == 0) {
	mas.sort( (a,b) => a-b );
	var count = 0;
	for (var i=0; i<n-1; i++) {
	if (mas[i] != mas[i+1]) count++;
	}
	print(count+1);
}

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

for (var i=0; i<n; i++) {
	var s = readline();
	mas[i] = s.indexOf('S') - s.indexOf('G');
	if (mas[i] < 0) {
		print(-1);
		var ans = -1;
		break;
	}
}

if (ans == 0) {
	mas.sort( (a,b) => a-b );
	var count = 0;
	for (var i=0; i<n-1; i++) {
	if (s[i] != s[i+1]) count++;
	}
	print(count);
}

print(function(n, m){
	var a=[];
	for(var i=0; i<n; i++){
		var s=readline();
		var G=s.indexOf('G');
		var S=s.indexOf('S');
		if(S<G){
			return -1;
		}else{
			a.push([S-G]);
		}
	}
	a.sort(function(a,b){return a-b});
	var ans=0;
	for(var i=1;i<n;i++){
		if(a[i]!==a[i-1]) ans++;
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));


Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.

Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.

NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.In the third sample, the optimal solution is {3, 5} and {7}.

var a = readline().split(' ');
var n = parseInt(a[0]);
var k = parseInt(a[1]);
a = []
var sa = readline().split(' ');
for(var i = 0; i < n; i++) {
    a[i] = parseInt(sa[i]);
}
var ans = 0;
if(k >= n) ans = a[n-1];
else {
    for(var i=0;i<n-k;i++) {
        var tmp = a[i] + a[2*n-2*k-1-i];
        if(tmp > ans) ans = tmp;
    }
    for(var i=2*n-2*k;i<n;i++) {
        if(a[i] > ans) ans = a[i];
    }
}
print(ans);


In this problem you will write a simple generator of Brainfuck (https://en.wikipedia.org/wiki/Brainfuck) calculators.You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of evaluating this expression.We use a fairly standard Brainfuck interpreter for checking the programs: 30000 memory cells. memory cells store integers from 0 to 255 with unsigned 8-bit wraparound. console input (, command) is not supported, but it's not needed for this problem.

The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive. The calculations result is guaranteed to be an integer between 0 and 255, inclusive (results of intermediary calculations might be outside of these boundaries).

Output a Brainfuck program which, when executed, will print the result of evaluating this expression. The program must be at most 5000000 characters long (including the non-command characters), and its execution must be complete in at most 50000000 steps.

NoteYou can download the source code of the Brainfuck interpreter by the link http://assets.codeforces.com/rounds/784/bf.cpp. We use this code to interpret outputs.

const input = readline();
const str = eval(input).toString();
const result = [">++++++++[<++++++>-]<"];
var last = 48;
for (var i = 0, len = str.length; i < len; i++) {
  var current = str.charCodeAt(i);
  var diff = current - last;
  result.push(diff >= 0 ? "+".repeat(diff) : "-".repeat(-diff), ".");
  last = current;
}
print(result.join(""));

var res = eval(readline()).toString();
for(i=0; i<res.length; i++)	{
	for(j=0; j<res[i].charCodeAt(0); j++)	{
		write('+');
	}
	write(".>");
}

var input=readline();
var operands=input.split(/[+-]/);
for(var i=0;i<operands.length;i++){
	var s='';
	for(var j=0;j<operands[i];j++)
		s+='+';
	print(s+'>');
}
var operators=input.split(/\d/);
for(var i=operators.length-2;i>0;i--){
	var s='<[<'+operators[i]+'>-]';
	print(s);
}
print('<');
print('++++++++++++++++++++++++++++++++++++++++++++++++.');

var input=readline();
var operands=input.split(/[+-]/);
for(var i=0;i<operands.length;i++){
	var s='';
	for(var j=0;j<operands[i];j++)
		s+='+';
	print(s+'>');
}
var operators=input.split(/\d/);
for(var i=operators.length-2;i>0;i--){
	var s='<[';
	for(var j=0;j<i;j++)
		s+='<';
	s+=operators[i];
	for(var j=0;j<i;j++)
		s+='>';
	s+='-]';
	print(s);
}
print('<');
print('++++++++++++++++++++++++++++++++++++++++++++++++.');

var input=readline();
var operands=input.split(/[+-]/);
for(var i=0;i<operands.length;i++){
	var s='';
	for(var j=0;j<operands[i];j++)
		s+='+';
	print(s+'>');
}
var operators=input.split(/[0-9]+/);
for(var i=operators.length-2;i>0;i--){
	var s='<[<'+operators[i]+'>-]<';
	print(s);
}
print('++++++++++++++++++++++++++++++++++++++++++++++++.');


Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.

The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.

Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.

NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.

var n = +readline(), a = readline().split(" ").map(Number);
var x = 0, bool = [], proof;

for(var i = 0; i < n; i++){
	bool[i] = true;
}

for(var i = 0; ;i++){
	proof = true;

	for(var j = 0; j < n; j++){
		if(a[j] <= x){
			if(bool[j]){
				x++;
				bool[j] = false;
			}
			else{
				continue;
			}
		}
		else{
			proof = false;
		}
	}

	if(proof){
		write(i);
		break;
	}

	a = a.reverse();
	bool = bool.reverse();
}

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var List = __webpack_require__(1);
	var n = List.map(parseInt, readline().split(' '))[0];
	var a = List.map(parseInt, readline().split(' '));
	var level = 0;
	var changes = 0;
	var i = 0;
	var di = 1;
	while (true) {
	    while (i >= 0 && i < n) {
	        if (a[i] <= level) {
	            level++;
	            a[i] = n + 1;
	        }
	        i += di;
	    }
	    if (level == n)
	        break;
	    i -= di;
	    di = -di;
	    changes++;
	}
	print(changes);

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	var Prelude_1 = __webpack_require__(2);
	function add(xs, ys) {
	    return xs.concat(ys);
	}
	exports.add = add;
	function head(xs) {
	    return xs[0];
	}
	exports.head = head;
	function last(xs) {
	    return xs[xs.length - 1];
	}
	exports.last = last;
	function tail(xs) {
	    return xs.slice(1);
	}
	exports.tail = tail;
	function init(xs) {
	    return xs.slice(0, xs.length - 1);
	}
	exports.init = init;
	function map(f, xs) {
	    var result = new Array(xs.length);
	    for (var i = 0; i < xs.length; i++) {
	        result[i] = f(xs[i]);
	    }
	    return result;
	}
	exports.map = map;
	function reverse(xs) {
	    return xs.slice().reverse();
	}
	exports.reverse = reverse;
	function intersperse(x, xs) {
	    if (xs.length == 0) {
	        return [];
	    }
	    var result = new Array(xs.length + xs.length - 1);
	    for (var i = 0; i + 1 < xs.length; i++) {
	        result[i + i] = xs[i];
	        result[i + i + 1] = x;
	    }
	    result[result.length - 1] = xs[xs.length - 1];
	    return result;
	}
	exports.intersperse = intersperse;
	function intercalate(xs, xss) {
	    return concat(intersperse(xs, xss));
	}
	exports.intercalate = intercalate;
	function foldl(f, initial, xs) {
	    var result = initial;
	    for (var i = 0; i < xs.length; i++) {
	        result = f(result, xs[i]);
	    }
	    return result;
	}
	exports.foldl = foldl;
	function foldr(f, initial, xs) {
	    var result = initial;
	    for (var i = xs.length - 1; i >= 0; i--) {
	        result = f(xs[i], result);
	    }
	    return result;
	}
	exports.foldr = foldr;
	function concat(xss) {
	    var total = sum(map(function (xs) { return xs.length; }, xss));
	    var result = new Array(total);
	    var m = 0;
	    for (var i = 0; i < xss.length; i++) {
	        var xs = xss[i];
	        for (var j = 0; j < xs.length; j++) {
	            result[m++] = xs[j];
	        }
	    }
	    return result;
	}
	exports.concat = concat;
	function sum(xs) {
	    var result = 0;
	    for (var i = 0; i < xs.length; i++) {
	        result += xs[i];
	    }
	    return result;
	}
	exports.sum = sum;
	function product(xs) {
	    var result = 1;
	    for (var i = 0; i < xs.length; i++) {
	        result *= xs[i];
	    }
	    return result;
	}
	exports.product = product;
	function sort(xs, compare) {
	    return copy(xs).sort(compare);
	}
	exports.sort = sort;
	function sortInPlace(xs, compare) {
	    xs.sort(compare);
	    return xs;
	}
	exports.sortInPlace = sortInPlace;
	function maximumInRange(xs, s, e) {
	    var result = xs[s];
	    for (var i = s + 1; i <= e; i++) {
	        if (result < xs[i])
	            result = xs[i];
	    }
	    return result;
	}
	exports.maximumInRange = maximumInRange;
	function maximum(xs) {
	    return maximumInRange(xs, 0, xs.length - 1);
	}
	exports.maximum = maximum;
	function maximumInRangeWith(xs, s, e, f) {
	    var result = f(xs[s]);
	    for (var i = s + 1; i <= e; i++) {
	        var candidate = f(xs[i]);
	        if (result < candidate)
	            result = candidate;
	    }
	    return result;
	}
	exports.maximumInRangeWith = maximumInRangeWith;
	function maximumWith(xs, f) {
	    return maximumInRangeWith(xs, 0, xs.length - 1, f);
	}
	exports.maximumWith = maximumWith;
	function minimumInRange(xs, s, e) {
	    var result = xs[s];
	    for (var i = s + 1; i <= e; i++) {
	        if (result > xs[i])
	            result = xs[i];
	    }
	    return result;
	}
	exports.minimumInRange = minimumInRange;
	function minimum(xs) {
	    return minimumInRange(xs, 0, xs.length - 1);
	}
	exports.minimum = minimum;
	function minimumInRangeWith(xs, s, e, f) {
	    var result = f(xs[s]);
	    for (var i = s + 1; i <= e; i++) {
	        var candidate = f(xs[i]);
	        if (result > candidate)
	            result = candidate;
	    }
	    return result;
	}
	exports.minimumInRangeWith = minimumInRangeWith;
	function minimumWith(xs, f) {
	    return minimumInRangeWith(xs, 0, xs.length - 1, f);
	}
	exports.minimumWith = minimumWith;
	function replicate(n, x) {
	    var result = new Array(n);
	    for (var i = 0; i < result.length; i++) {
	        result[i] = x;
	    }
	    return result;
	}
	exports.replicate = replicate;
	function take(n, xs) {
	    return xs.slice(0, n);
	}
	exports.take = take;
	function drop(n, xs) {
	    return xs.slice(n);
	}
	exports.drop = drop;
	function splitAt(n, xs) {
	    return [take(n, xs), drop(n, xs)];
	}
	exports.splitAt = splitAt;
	function takeWhile(f, xs) {
	    for (var i = 0; i < xs.length; i++) {
	        if (!f(xs[i])) {
	            return xs.slice(0, i);
	        }
	    }
	    return xs.slice();
	}
	exports.takeWhile = takeWhile;
	function dropWhile(f, xs) {
	    for (var i = 0; i < xs.length; i++) {
	        if (!f(xs[i])) {
	            return xs.slice(i);
	        }
	    }
	    return [];
	}
	exports.dropWhile = dropWhile;
	function group(xs) {
	    if (xs.length == 0)
	        return [];
	    var result = [];
	    var last = [xs[0]];
	    for (var i = 1; i < xs.length; i++) {
	        if (last[0] === xs[i]) {
	            last.push(xs[i]);
	        }
	        else {
	            result.push(last);
	            last = [xs[i]];
	        }
	    }
	    result.push(last);
	    return result;
	}
	exports.group = group;
	function nub(xs) {
	    if (xs.length == 0)
	        return [];
	    var result = [];
	    result.push(xs[0]);
	    for (var i = 1; i < xs.length; i++) {
	        if (xs[i] !== xs[i - 1]) {
	            result.push(xs[i]);
	        }
	    }
	    return result;
	}
	exports.nub = nub;
	function filter(f, xs) {
	    var result = [];
	    for (var i = 0; i < xs.length; i++) {
	        if (f(xs[i]))
	            result.push(xs[i]);
	    }
	    return result;
	}
	exports.filter = filter;
	function zip(xs, ys) {
	    var n = Prelude_1.min(xs.length, ys.length);
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = [xs[i], ys[i]];
	    }
	    return result;
	}
	exports.zip = zip;
	function unzip(xs) {
	    var r1 = new Array(xs.length);
	    var r2 = new Array(xs.length);
	    for (var i = 0; i < xs.length; i++) {
	        r1[i] = xs[i][0];
	        r2[i] = xs[i][1];
	    }
	    return [r1, r2];
	}
	exports.unzip = unzip;
	function range(from, to) {
	    var result = Array(to - from + 1);
	    for (var i = from; i <= to; i++) {
	        result[i - from] = i;
	    }
	    return result;
	}
	exports.range = range;
	function copy(xs) {
	    return xs.slice(0);
	}
	exports.copy = copy;
	function apply_permutation(p, xs) {
	    var n = xs.length;
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = xs[p[i]];
	    }
	    return result;
	}
	exports.apply_permutation = apply_permutation;
	function next_permutation(p) {
	    var n = p.length;
	    if (n < 2)
	        return null;
	    var r = copy(p);
	    var k = n - 2;
	    for (; k >= 0 && r[k] >= r[k + 1]; k--)
	        ;
	    if (k < 0)
	        return null;
	    for (var i = k + 1, j = n - 1; i < j; i++, j--) {
	        var t_1 = r[i];
	        r[i] = r[j];
	        r[j] = t_1;
	    }
	    var next = k + 1;
	    for (; r[next] <= r[k]; next++)
	        ;
	    var t = r[k];
	    r[k] = r[next];
	    r[next] = t;
	    return r;
	}
	exports.next_permutation = next_permutation;
	function create(n, value) {
	    return replicate(n, value);
	}
	exports.create = create;
	function createWith(n, f) {
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = f(i);
	    }
	    return result;
	}
	exports.createWith = createWith;
	function create2D(n1, n2, value) {
	    return map(function (_) { return replicate(n2, value); }, replicate(n1, 0));
	}
	exports.create2D = create2D;
	function create2DWith(n1, n2, f) {
	    var result = new Array(n1);
	    for (var i = 0; i < n1; i++) {
	        result[i] = new Array(n2);
	        for (var j = 0; j < n2; j++) {
	            result[i][j] = f(i, j);
	        }
	    }
	    return result;
	}
	exports.create2DWith = create2DWith;

/***/ },
/* 2 */
/***/ function(module, exports) {

	function min(a, b) {
	    return a < b ? a : b;
	}
	exports.min = min;
	function max(a, b) {
	    return a < b ? b : a;
	}
	exports.max = max;
	function curry(f) {
	    return function (x) { return function (y) { return f(x, y); }; };
	}
	exports.curry = curry;
	function uncurry(f) {
	    return function (x, y) { return f(x)(y); };
	}
	exports.uncurry = uncurry;
	function id(x) {
	    return x;
	}
	exports.id = id;
	function constant(x) {
	    return function (_) { return x; };
	}
	exports.constant = constant;
	function flip(f) {
	    return function (y) { return function (x) { return f(x)(y); }; };
	}
	exports.flip = flip;
	function flip2(f) {
	    return function (y, x) { return f(x, y); };
	}
	exports.flip2 = flip2;
	function compose(g, f) {
	    return function (x) { return g(f(x)); };
	}
	exports.compose = compose;
	function gcd(a, b) {
	    var r = a % b;
	    while (r !== 0) {
	        a = b;
	        b = r;
	        r = a % b;
	    }
	    return b;
	}
	exports.gcd = gcd;

/***/ }
/******/ ]);

'use strict';

/*let input = `
7
0 3 1 0 5 2 6
`.trim().split('\n');
function print(output) {
	console.log(output);
}
function readline() {
	return input.shift();
}
*/
//code

var n = Number(readline());
var coveredComputers = [],
    directionChanges = 0,
    i = 0,
    direction = 1;
var infoRequired = readline().split(' ').map(Number);

while (coveredComputers.length != n) {
	if (i >= n || i < 0) {
		direction *= -1;
		directionChanges++;
		i += direction * 2;
	}
	if (coveredComputers.indexOf(i) === -1) {
		if (infoRequired[i] <= coveredComputers.length) {
			coveredComputers.push(i);
		}
	}
	i += direction;
}
print(directionChanges);

n = readline();
a = readline().split(" ").map(Number);

answer = -1;
hacked = 0;

while (hacked < n) {
	answer += 1;
	if (answer % 2 == 0) {
		// right
		for (var i = 0; i < a.length; i++) {
			if (a[i] <= hacked && a[i] != -1) {
				a[i] = -1;
				hacked += 1;
			}
		}
	} else {
		for (var i = a.length-1; i >= 0; --i) {
			if (a[i] <= hacked && a[i] != -1) {
				a[i] = -1;
				hacked += 1;
			}
		}
	}

}

write(answer);