A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $$$l$$$ nanoseconds, where $$$l$$$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $$$2$$$ nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of Dima's sequence. The second line contains string of length $$$n$$$, consisting of characters "(" and ")" only.

Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.

NoteIn the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $$$4 + 2 = 6$$$ nanoseconds.

const processData = (lines) => {
  const s = lines[1].split('')

  let balance = 0

  // const prefix = []
  let acc = 0
  let neg = false
  let sum = 0
  let peak = 0
  for (let j =0; j<s.length; j++) {
    const ch = s[j]
    if (ch === '(') {
      acc++
      // prefix.push(acc)
      balance++
    } else {
      acc--
      // prefix.push(acc)
      balance--
    }
    if (!neg && acc < 0) {
      neg = true
      peak = j
    }
    if (acc === 0) {
      if (neg) {
        // console.log(j, peak)
        sum += (j - peak)+1
      }
      neg = false
    }
  }
  // console.log(prefix)
  if (balance !== 0) {
    console.log(-1)
  } else {
    console.log(sum)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const init = () => {
  process.stdin.resume();
  process.stdin.setEncoding('utf-8');

  let inputString = '';
  let currentLine = 0;

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

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

    main();
  });

  global.readline = () => {
    return inputString[currentLine++];
  }
};

if (typeof readline === 'undefined') {
  init();
}

const print = (...args) => {
  console.log(...args);
};

const isBalanced = (s) => {
  let r_cnt = 0;
  let l_cnt = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] === ')') r_cnt++;
    if (s[i] === '(') l_cnt++;
  }
  return r_cnt === l_cnt;
};

const main = () => {
  let n = parseInt(readline());
  let s = readline();
  if (!isBalanced(s)) return print(-1);

  let needs = false;
  let l_cnt = 0;
  let r_cnt = 0;
  let left = n;
  let cnt = 0;
  for (let i = 0; i < n; i++) {
    if (s[i] === ')') r_cnt++;
    if (s[i] === '(') l_cnt++;
    // print({ r_cnt, l_cnt, left, i, needs });
    if (r_cnt > l_cnt) {
      left = Math.min(left, i);
      needs = true;
    } else if (needs && r_cnt === l_cnt) {
      needs = false;
      cnt += i - left + 1;
      left = n;
    }
  }
  print(cnt)
};

function main(raw) {
    var lines = raw.trim().split("\n").map(function (l) { return l.trim(); });
    var l = parseInt(lines.shift(), 10);
    console.log(solve(l, lines.shift()));
}
function solve(l, s) {
    var cnt = 0;
    var cval = 0;
    var countingwrong = false;
    var failcnt = 0;
    for (var i = 0; i < l; i++) {
        if (s[i] === "(") {
            cval++;
        }
        else {
            cval--;
        }
        if (countingwrong) {
            if (cval === 0) {
                failcnt++;
                cnt += failcnt;
                failcnt = 0;
                countingwrong = false;
            }
            else {
                failcnt++;
            }
        }
        else if (cval < 0) {
            countingwrong = true;
            failcnt++;
        }
    }
    if (cval !== 0) {
        return -1;
    }
    return cnt;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var n = +readline();
  var str = readline();

  var bracketsSum = 0;
  var wrongBracketsSum = 0;
  for (var i = 0; i < str.length; i++) {
    if (str[i] === "(") {
      if (bracketsSum === -1) {
        wrongBracketsSum++;
      }
      bracketsSum++;
    }
    if (str[i] === ")") {
      bracketsSum--;
    }
    if (bracketsSum < 0) {
      wrongBracketsSum++;
    }
  }
  if (bracketsSum !== 0) {
    print(-1);
    return;
  }
  print(wrongBracketsSum);
}
main()

const processData = (lines) => {
  const s = lines[1].split('')

  let balance = 0

  const prefix = []
  let acc = 0
  let neg = false
  let sum = 0
  let peak = 0
  for (let j =0; j<s.length; j++) {
    const ch = s[j]
    if (ch === '(') {
      acc++
      prefix.push(acc)
      balance++
    } else {
      acc--
      prefix.push(acc)
      balance--
    }
    if (!neg && acc < 0) {
      neg = true
      peak = j
    }
    if (acc === 0) {
      if (neg) {
        sum += j - peak
      }
      neg = false
    }
  }
  if (balance !== 0) {
    console.log(-1)
  } else {
    console.log(sum)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const s = lines[1].split('')

  let balance = 0

  // const prefix = []
  let acc = 0
  let neg = false
  let sum = 0
  let peak = 0
  for (let j =0; j<s.length; j++) {
    const ch = s[j]
    if (ch === '(') {
      acc++
      // prefix.push(acc)
      balance++
    } else {
      acc--
      // prefix.push(acc)
      balance--
    }
    if (!neg && acc < 0) {
      neg = true
      peak = j
    }
    if (acc === 0) {
      if (neg) {
        console.log(j, peak)
        sum += (j - peak)+1
      }
      neg = false
    }
  }
  // console.log(prefix)
  if (balance !== 0) {
    console.log(-1)
  } else {
    console.log(sum)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var n = +readline();
  var str = readline();

  var bracketsSum = 0;
  var wrongBracketsSum = 0;
  for (var i = 0; i < str.length; i++) {
    if (str[i] === "(") {
      if (bracketsSum === -1) {
        wrongBracketsSum++;
      }
      bracketsSum++;
    }
    if (str[i] === ")") {
      bracketsSum--;
    }
    if (bracketsSum < 0) {
      wrongBracketsSum++;
    }
  }
  if (bracketsSum !== 0) {
    print(-1);
  }
  print(wrongBracketsSum);
}
main()


Bakry faced a problem, but since he's lazy to solve it, he asks for your help.You are given a tree of $$$n$$$ nodes, the $$$i$$$-th node has value $$$a_i$$$ assigned to it for each $$$i$$$ from $$$1$$$ to $$$n$$$. As a reminder, a tree on $$$n$$$ nodes is a connected graph with $$$n-1$$$ edges.You want to delete at least $$$1$$$, but at most $$$k-1$$$ edges from the tree, so that the following condition would hold:For every connected component calculate the bitwise XOR of the values of the nodes in it. Then, these values have to be the same for all connected components.Is it possible to achieve this condition?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 5 \cdot 10^4)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \leq k \leq n \leq 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i\neq v_i$$$), which means that there's an edge between nodes $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, you should output a single string. If you can delete the edges according to the conditions written above, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteIt can be shown that the objection is not achievable for first, third, and fifth test cases.In the second test case, you can just remove all the edges. There will be $$$5$$$ connected components, each containing only one node with value $$$3$$$, so the bitwise XORs will be $$$3$$$ for all of them.In the fourth test case, this is the tree: .You can remove an edge $$$(4,5)$$$The bitwise XOR of the first component will be, $$$a_1 \oplus a_2 \oplus a_3 \oplus a_4 = 1 \oplus 6 \oplus 4 \oplus 1 = 2$$$ (where $$$\oplus$$$ denotes the bitwise XOR). The bitwise XOR of the second component will be, $$$a_5 = 2$$$.

'use strict';

function solve(n, m, a, b) {
  let t = a.reduce((a, b) => a ^ b, 0);
  if (t === 0) return 'YES';
  if (m < 3) return 'NO';
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        d = new Array(n).fill(0);
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, d[j]++, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v] of b) {
    add(u - 1, v - 1);
    add(v - 1, u - 1);
  }
  const vis = new Array(n);
  let res = 0;
  const dfs1 = RTI(i => {
    vis[i] = 1;
    const inside = () => {
      let params = [];
      for (let k = h[i]; k !== -1; k = ne[k]) {
        const j = e[k];
        if (vis[j]) continue;
        params.push([j]);
      }
      return params;
    };
    const after = (...result) => {
      let ans = result.reduce((a, b) => a ^ b, 0) ^ a[i];
      if (ans === t) {
        res++;
        ans = 0;
      }
      return ans;
    };
    return [inside, after];
  });
  dfs1(0);
  return res >= 2 ? 'YES' : 'NO';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = result => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

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++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))
        l += n - 1
        console.log(solve(n, k, arr, edges))
    }
// })()
})

function solve(n, k, arr, edges) {
    const xor = arr.reduce((s, x) => s ^ x, 0)
    if (!xor) return 'YES'
    if (k - 1 < 2) return 'NO'
// console.log(xor)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'
}
function dfs(adj, r, visited, arr, target) {
    const stack = [[r, 0, -1]]
    const xor = []
    let found = 0
    let cut = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            cut++
            xor[u] = arr[u - 1]
            nb.forEach(v => {
                if (v !== p) xor[u] ^= xor[v]
            })
            if (xor[u] === target) {
                found++
                // console.log('found', cut, arr.length)
                if (found === 2) return true
                xor[u] = 0
            }
            stack.pop()
        }
    }
    // console.log(xor)
    return false
}

'use strict';

function solve(n, m, a, b) {
  let t = a.reduce((a, b) => a ^ b, 0);
  if (t === 0) return 'YES';
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        d = new Array(n).fill(0);
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, d[j]++, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v] of b) {
    add(u - 1, v - 1);
    add(v - 1, u - 1);
  }
  const vis = new Array(n);
  let res = 0;
  const dfs1 = RTI(i => {
    vis[i] = 1;
    const inside = () => {
      let params = [];
      for (let k = h[i]; k !== -1; k = ne[k]) {
        const j = e[k];
        if (vis[j]) continue;
        params.push([j]);
      }
      return params;
    };
    const after = (...result) => {
      let ans = result.reduce((a, b) => a ^ b, 0) ^ a[i];
      if (ans === t) {
        res++;
        ans = 0;
      }
      return ans;
    };
    return [inside, after];
  });
  dfs1(0);
  return res >= 2 ? 'YES' : 'NO';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = result => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

function solve(n, m, a, b) {
  let t = a.reduce((a, b) => a ^ b, 0);
  if (t === 0) return 'YES';
  const h = new Array(n).fill(-1),
        e = [],
        ne = [],
        d = new Array(n).fill(0);
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, d[j]++, ne[idx] = h[i], h[i] = idx++;
  };
  for (let [u, v] of b) {
    add(u - 1, v - 1);
    add(v - 1, u - 1);
  }
  const vis = new Array(n);
  let res = 0;
  const dfs = i => {
    vis[i] = 1;
    let ans = 0;
    for (let k = h[i]; k !== -1; k = ne[k]) {
      const j = e[k];
      if (vis[j]) continue;
      let sum = dfs(j);
      if (sum === t) {
        res++;
        sum = 0;
      }
      ans ^= sum;
      if (ans === t) {
        res++;
        ans = 0;
      }
    }
    return ans ^ a[i];
  };
  dfs(0);
  return res > 2 ? 'YES' : 'NO';
}

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

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

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++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))
        l += n - 1
        console.log(solve(n, k, arr, edges))
    }
// })()
})

function solve(n, k, arr, edges) {
    const xor = arr.reduce((s, x) => s ^ x, 0)
    if (!xor) return 'YES'
// console.log(xor)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'
}
function dfs(adj, r, visited, arr, target) {
    const stack = [[r, 0, -1]]
    const xor = []
    let found = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            xor[u] = arr[u - 1]
            nb.forEach(v => {
                if (v !== p) xor[u] ^= xor[v]
            })
            if (xor[u] === target) {
                found++
                if (found === 2 && u !== r) return true
                xor[u] = 0
            }
            stack.pop()
        }
    }
    // console.log(xor)
    return false
}

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++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))
        l += n - 1
        console.log(solve(n, k, arr, edges))
    }
// })()
})

function solve(n, k, arr, edges) {
    const xor = arr.reduce((s, x) => s ^ x, 0)
    if (!xor) return 'YES'
// console.log(xor)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'
}
function dfs(adj, r, visited, arr, target) {
    const stack = [[r, 0, -1]]
    const xor = []
    let found = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            xor[u] = arr[u - 1]
            nb.forEach(v => {
                if (v !== p) xor[u] ^= xor[v]
            })
            if (xor[u] === target) {
                found++
                if (found === 2) return true
                xor[u] = 0
            }
            stack.pop()
        }
    }
    // console.log(xor)
    return false
}

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++]
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))
        l += n - 1
        console.log(solve(n, k, arr, edges))
    }
// })()
})

function solve(n, k, arr, edges) {
    const xor = arr.reduce((s, x) => s ^ x, 0)
    if (!xor) return 'YES'

    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    return dfs(adj, 1, {}, arr, xor) ? 'YES' : 'NO'
}
function dfs(adj, r, visited, arr, target) {
    const stack = [[r, 0, -1]]
    const xor = []
    let found = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            xor[u] = arr[u]
            nb.forEach(v => {
                if (v !== p) xor[u] ^= xor[v]
            })
            if (xor[u] === target) {
                found++
                if (found === 2) return true
                xor[u] = 0
            }
            stack.pop()
        }
    }
    return false
}


You have an array of integers (initially empty).You have to perform $$$q$$$ queries. Each query is of one of two types:   "$$$1$$$ $$$x$$$" — add the element $$$x$$$ to the end of the array;  "$$$2$$$ $$$x$$$ $$$y$$$" — replace all occurrences of $$$x$$$ in the array with $$$y$$$. Find the resulting array after performing all the queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — the number of queries. Next $$$q$$$ lines contain queries (one per line). Each query is of one of two types:    "$$$1$$$ $$$x$$$" ($$$1 \le x \le 5 \cdot 10^5$$$);  "$$$2$$$ $$$x$$$ $$$y$$$" ($$$1 \le x, y \le 5 \cdot 10^5$$$).  It's guaranteed that there is at least one query of the first type.

In a single line, print $$$k$$$ integers — the resulting array after performing all the queries, where $$$k$$$ is the number of queries of the first type.

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

	main();
});

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

function main() {
	var q = +readLine();
	var queries = [];
	for (let i = 0; i < q; i++) {
		queries.push(readLine().split(" ").map(Number));
	}

	let value = [];
	let nax = 500000;
	for (let i = 0; i <= nax; i++) {
		value.push(i);
	}

	let ans = [];
	for (let i = q - 1; i >= 0; i--) {
		if (queries[i][0] == 1) {
			ans.push(value[queries[i][1]]);
		} else {
			value[queries[i][1]] = value[queries[i][2]];
		}
	}
	ans.reverse();
	console.log(ans.join(" "));
}

    "use strict";

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

let inputString = "";
let currentLine = 0;

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

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

	main();
});

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

function find(req, values) {
	if (values[req] == req) {
		return req;
	}
	return (values[req] = find(values[req], values));
}
function main() {
	var q = +readLine();
	var queries = [];
	for (let i = 0; i < q; i++) {
		queries.push(readLine().split(" ").map(Number));
	}

	let value = [];
	let nax = 500000;
	for (let i = 0; i <= nax; i++) {
		value.push(i);
	}

	let ans = [];
	for (let i = q - 1; i >= 0; i--) {
		if (queries[i][0] == 1) {
			ans.push(find(queries[i][1], value));
		} else {
			value[find(queries[i][1], value)] = find(queries[i][2], value);
		}
	}
	ans.reverse();
	console.log(ans.join(" "));
}


You are given a sequence $$$a=[a_1,a_2,\dots,a_n]$$$ consisting of $$$n$$$ positive integers.Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $$$a[l,r]$$$ a segment of the sequence $$$a$$$ with the left end in $$$l$$$ and the right end in $$$r$$$, i.e. $$$a[l,r]=[a_l, a_{l+1}, \dots, a_r]$$$.For example, if $$$a=[31,4,15,92,6,5]$$$, then $$$a[2,5]=[4,15,92,6]$$$, $$$a[5,5]=[6]$$$, $$$a[1,6]=[31,4,15,92,6,5]$$$ are segments.We split the given sequence $$$a$$$ into segments so that:   each element is in exactly one segment;  the sums of elements for all segments are equal. For example, if $$$a$$$ = [$$$55,45,30,30,40,100$$$], then such a sequence can be split into three segments: $$$a[1,2]=[55,45]$$$, $$$a[3,5]=[30, 30, 40]$$$, $$$a[6,6]=[100]$$$. Each element belongs to exactly segment, the sum of the elements of each segment is $$$100$$$.Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $$$3$$$.Find the minimum thickness among all possible splits of the given sequence of $$$a$$$ into segments in the required way.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case is described by two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the length of the sequence $$$a$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.

For each test case, output one integer — the minimum possible thickness of a split of the sequence $$$a$$$ into segments. Note that there always exist a split, you can always consider whole sequence as one segment.

NoteThe split in the first test case is explained in the statement, it can be shown that it is optimal.In the second test case, it is possible to split into segments only by leaving a single segment. Then the thickness of this split is equal to the length of the entire sequence, that is, $$$4$$$.In the third test case, the optimal split will be $$$[10, 55], [35, 30], [65]$$$. The thickness of the split equals to $$$2$$$.In the fourth test case possible splits are:  $$$[4] + [1, 1, 1, 1] + [4]$$$;  $$$[4, 1, 1] + [1, 1, 4]$$$.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    const helper = (l, r, sum) => {
      let s = 0,
        dis = -1;
      while (r < n) {
        s += arr[r];
        if (s === sum) {
          s = 0;
          dis = Math.max(r - l + 1, dis);
          r++;
          l = r;
        } else r++;
      }

      return s === 0 ? dis : -1;
    };
    if (arr.length === 1) {
      console.log(1);
      continue;
    }
    let sum = arr[0],
      ans = Infinity;
    for (let i = 1; i < n; i++) {
      let k = helper(i, i, sum);
      if (k !== -1) ans = Math.min(ans, Math.max(i, k));
      sum += arr[i];
    }
    console.log(ans === Infinity ? n : ans);
  }
};
solve();

/*
** Template
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let n = parseInt(readline())
        let a = readline().split(' ').map(Number)
        console.log(solve(n, a))
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (n, a) => {
    let total = 0
    let res = n
    for (let i = 0; i < n; i++) {
        total += a[i]
        let ans = i + 1
        let sum = 0
        let found = true
        let k = i

        for (let j = i + 1; j < n; j++) {
            if (sum + a[j] == total) {
                ans = Math.max(ans, (j - k))
                k = j
                sum = 0
            } else if ((sum + a[j]) < total) {
                sum += a[j]
            } else {
                found = false
                break
            }
        }

        if (found && sum == 0) res = Math.min(ans, res)

    }
    return res
}

const isOdd = (num) => num & 1
const isEven = (num) => !(num & 1)
const minOfArray = (arr) => Math.min.apply(null, arr)
const maxOfArray = (arr) => Math.max.apply(null, arr)
const uniqueArray = (arr) => [...new Set(arr)]
const sortArray = (arr) => arr.sort((a, b) => a - b)
const sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const sum = Array(n)
    for (let i = 0; i < arr.length; i++) {
        sum[i] = arr[i]
        if (i) sum[i] += sum[i - 1]
    }
    let r = n
    for (let i = 1; i <= arr.length; i++) {
        const s = sum[i - 1]
        if (sum[n - 1] % s) continue
        let p = i
        let ok = true
        let temp = i
        while (p < n) {
            let j = p
            let now = arr[j]
            while (now < s && j + 1 < n) {
                now += arr[++j]
            }
            if (now !== s) {
                ok = false
                break
            }
            temp = Math.max(temp, j - p + 1)
        // console.log(s, ok, temp, '-', p, j, now)
            p = j + 1
        }
        if (ok) r = Math.min(r, temp)
    }
    return r
}

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n);
  let res = n,
      t = 0;
  next: for (let i = 0; i < n; i++) {
    let ans = i + 1,
        sum = 0,
        pre = i + 1;
    t += a[i];
    for (let j = i + 1; j < n; j++) {
      sum += a[j];
      if (sum === t) {
        sum = 0;
        ans = Math.max(ans, j - pre + 1);
        pre = j + 1;
      } else if (sum > t) {
        continue next;
      }
    }
    if (sum === 0 && pre === n) {
      res = Math.min(res, ans);
    }
  }
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8')
.split(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    const helper = (l, r, sum) => {
      let s = 0,
        dis = -1;
      while (r < n) {
        s += arr[r];
        if (s === sum) {
          s = 0;
          dis = Math.max(r - l + 1, dis);
          r++;
          l = r;
        }
        r++;
      }

      return dis;
    };
    let sum = arr[0],
      ans = Infinity;
    for (let i = 1; i < n; i++) {
      let k = helper(i, i, sum);
      if (k !== -1) ans = Math.min(ans, k);
      sum += arr[i];
    }
    console.log(ans === Infinity ? n : ans);
  }
};
solve();


There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.

The first line contains the positive integer n (1 ≤ n ≤ 200 000) — the number of particles.  The second line contains n symbols "L" and "R". If the i-th symbol equals "L", then the i-th particle will move to the left, otherwise the i-th symbol equals "R" and the i-th particle will move to the right. The third line contains the sequence of pairwise distinct even integers x1, x2, ..., xn (0 ≤ xi ≤ 109) — the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order.

In the first line print the only integer — the first moment (in microseconds) when two particles are at the same point and there will be an explosion.  Print the only integer -1, if the collision of particles doesn't happen.

NoteIn the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point.

var nbOfElement = Number(readline());
var direction = readline();
var elements = readline()
  .split(' ')
  .map(Number);

var pair = [];
for (var i = 1; i < nbOfElement; ++i) {
  if (direction[i - 1] === 'R' && direction[i] === 'L') {
    pair.push([i - 1, i]);
  }
}

var smallestPair = Infinity;
for (var i = 0; i < pair.length; i++) {
  smallestPair = Math.min(
    smallestPair,
    Math.round((elements[pair[i][1]] - elements[pair[i][0]]) / 2)
  );
}

if (pair.length === 0) {
  print(-1);
} else {
  print(smallestPair);
}

var n=parseInt(readline());
var d=readline();
d += "E";
var pos=readline().split(' ');
var mn = 1000000000;
function go(el, i, a){
	if(d[i] == 'R' && d[i+1] == 'L'){
		mn = Math.min(mn, (a[i+1] - a[i])/2);
	};
};
pos.forEach(go);
if(mn != 1000000000){
	print(mn);
} else {
	print(-1);
};

var print = this.print || require('lol-io').print; //print --> outputs result and adds (enter)
var write = this.write || require('lol-io').write; //write --> creates output.txt with output
var readline = this.readline || require('lol-io').readline; //readline --> reads unread line of input.txt

var n, map, position, ans = [];

n = Number(readline());
map = readline().replace(/\r$/, '').split('');
position = readline().replace(/\r$/, '').split(' ').map(Number);

for (i = 0; i < n - 1; i++) {

    if (map[i] !== map[i + 1]　&& map[i] === 'R') {

        ans.push(Math.abs(position[i] - position[i + 1]) / 2);
    } else if (map === map[i + 1] && map[i] === 'L') {

        ans.push(position[i + 1] - position[i]);
    } else if (map === map[i + 1] && map[i] === 'R') {

        ans.push(position[i] - position[i + 1]);
    }
}

ans = ans.filter(x => x > 0);

if (ans.length === 0) {

    write(-1);
} else {

    write(Math.min(...ans));
}

(function() {
    var n = parseInt(readline());
    var dir  = readline();
    var arr = readline().split(" ").map(Number);

    var min = Infinity;

    for (var i = 0; i < dir.length - 1; i++) {
        if (dir[i] === 'R' && dir[i + 1] === 'L') {
            var low = (arr[i + 1] - arr[i]) / 2;
            if (low < min) {
                min = low;
            }
        }
    }

    print(min === Infinity? -1: min);

})();

function rda(){ return readline().split(" ").map(Number); };
function rdn(){ return +readline(); };

var n = rdn();
var coms = readline().split("");
var x = rda();

var ans = Infinity;
for(var i = 0; i < n-1; i++){
    if(coms[i] == "R" && coms[i+1] == "L"){
        ans = Math.min(ans, (x[i+1]-x[i])/2);
    }
}
ans = (ans == Infinity) ? -1 : ans;

write(ans);

(function() {
    var n = parseInt(readline());
    var dir  = readline();
    var arr = readline().split(" ").map(Number);

    var min = Infinity;

    for (var i = 0; i < dir.length - 1; i++) {
        if (dir[i] === 'R' && dir[i + 1] === 'L') {
            var low = (arr[i + 1] - arr[i]) / 2;
            if (low < min) {
                min = low;
            }
        }
    }

    print(min);

})();

(function() {
    var n = parseInt(readline());
    var dir  = readline();
    var arr = readline().split(" ").map(Number);

    var min = Infinity;
    var collision = [];

    while(dir.length) {
        var found = dir.indexOf('RL');
        collision.push(found);
        dir = dir.slice(found + 2);
    }

    if (!collision.length) {
        print(-1);
        return;
    }

    collision.forEach((col) => {
        var dist = (arr[col + 1] - arr[col])/ 2;
        if (dist < min) {
            min = dist;
        }
    });

    print(min);

})();

(function() {
    var n = parseInt(readline());
    var dir  = readline();
    var arr = readline().split(" ").map(Number);

    var min = Infinity;
    var collision = [];

    while(dir.length) {
        var found = dir.indexOf('RL');
        if (found === -1) {
            break;
        }
        collision.push(found);
        dir = dir.slice(found + 2);
    }

    if (!collision.length) {
        print(-1);
        return;
    }

    collision.forEach((col) => {
        var dist = (arr[col + 1] - arr[col])/ 2;
        if (dist < min) {
            min = dist;
        }
    });

    print(min);

})();


After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes.  The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 1 000 000), where ai is the identifier of the photo which got the i-th like.

Print the identifier of the photo which won the elections.

NoteIn the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got:  more likes than the photo with id 3;  as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.

var likesCount = parseInt(readline());
var likes = readline().split(' ').map(function (x) {return parseInt(x)})

var winnerId = -1
var map = {}

for (var i = 0; i < likesCount; i++) {
	var photoId = likes[i]

	if (map[photoId] === undefined) {
		map[photoId] = 0
	}
	var newLikesCount = ++map[photoId]

	if (winnerId === -1) {
		winnerId = photoId
	} else {
		if (newLikesCount > map[winnerId]) {
			winnerId = photoId
		}
	}
}

print(winnerId);

var count = readline();
var data = readline().split(" ");
var db = {};
var maxId = data[0];
data.forEach(function (v, c) {
    c = db[v] ? ++db[v] : (db[v] = 1);
    if (db[maxId] < c) { maxId = v }
});
print(maxId);

var l = readline().split(' ');
var n = +l[0];
var a = readline().split(' ');
var dat = {
};
var max = 0;
for (var i = 0; i < a.length; i++) {
	dat[a[i]] = dat[a[i]] ? dat[a[i]] + 1 : 1;
	max = dat[a[i]] > max ? dat[a[i]] : max;
}
var list = [];
for(var i in dat){
	if(dat[i]==max){
		list.push(i);
	}
}

for (var i = a.length - 1; i >= 0; i--) {
	if(list.length == 1){
		break;
	}
	var index = list.indexOf(a[i]);
	if(index!=-1){
		list.splice(index,1);
	}
}
print(list[0]);

var likes = readline().split(' '),
likeIds = readline().split(' '),
lastBiggest = {
    id: likeIds[0],
    count: 1
},
likeObj = {};
likeIds.map(function(el){
    likeObj[el] = typeof likeObj[el] !== "undefined" ? likeObj[el]+1 : 1;
    if (lastBiggest.count < likeObj[el]) {
        lastBiggest = {
            id: el,
            count: likeObj[el]
        }
    }
});
print(lastBiggest.id);

var readInt = () => parseInt(readline())
var readIntArray = () => readline().split(' ').map(item => parseInt(item))
Array.prototype.fill = function(value) {
    for (var i = 0; i < this.length; i++)
        this[i] = value
    return this
}
var n = readInt()
var l = readIntArray()
var l2 = []
l.forEach((i, index) => l2[i-1]={
    index: index,
    count: l2[i-1] ? l2[i-1].count+1 : 1
})
l2 = l2.filter(i => i)
var max = Math.max(...l2.map(i => i.count))
var ii = l2.filter(i => i.count === max).map(i => i.index)
print(l[Math.min(...ii)])


Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally:   If it is the first move, he chooses any element and deletes it;  If it is the second or any next move:   if the last deleted element was odd, Polycarp chooses any even element and deletes it;  if the last deleted element was even, Polycarp chooses any odd element and deletes it.   If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements of $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible sum of non-deleted elements of the array after end of the game.

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort((x,y)=>x-y);
    odd.sort((x,y)=> x-y);
    let num = 0;
    if (even.length > odd.length) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

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

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

  const arr = d.split(' ').map(Number).sort((a, b) => a - b);
  const even = arr.filter(x => x % 2 === 0);
  const odd = arr.filter(x => x % 2 === 1);
  let sum = arr.reduce((a, b) => a + b, 0);

  while (even.length && odd.length) {
    sum -= even.pop();
    sum -= odd.pop();
  }

  const max = Math.max(even.pop() || 0, odd.pop() || 0);
  sum -= max;

  console.log(sum);

  // const arr = d.split(' ').map(Number);
  // arr.sort((a, b) => a - b);
  // let ans = arr.reduce((a, b) => a + b, 0);
  // const even = [];
  // const odd = [];

  // for (let i = 0; i < arr.length; i++) {
  //   if (arr[i] % 2 === 0) {
  //     even.push(arr[i]);
  //   }
  //   else {
  //     odd.push(arr[i]);
  //   }
  // }

  // if (even.length > odd.length) {
  //   ans -= even.pop();

  //   while (even.length && odd.length) {
  //     ans -= odd.pop();
  //     ans -= even.pop();
  //   }
  // }
  // else if (odd.length > even.length) {
  //   ans -= odd.pop();

  //   while (even.length && odd.length) {
  //     ans -= even.pop();
  //     ans -= odd.pop();
  //   }
  // }
  // else {
  //   while (even.length && odd.length) {
  //     ans -= even.pop();
  //     ans -= odd.pop();
  //   }
  // }

  // console.log(ans);

  c++;
});

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

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

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  let ans = arr.reduce((a, b) => a + b, 0);
  const even = [];
  const odd = [];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      even.push(arr[i]);
    }
    else {
      odd.push(arr[i]);
    }
  }

  if (even.length > odd.length) {
    ans -= even.pop();

    while (even.length && odd.length) {
      ans -= odd.pop();
      ans -= even.pop();
    }
  }
  else if (odd.length > even.length) {
    ans -= odd.pop();

    while (even.length && odd.length) {
      ans -= even.pop();
      ans -= odd.pop();
    }
  }
  else {
    while (even.length && odd.length) {
      ans -= even.pop();
      ans -= odd.pop();
    }
  }

  console.log(ans);

  c++;
});

var stdin = "";
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { stdin += data; });
process.stdin.on('end', function () { main(stdin); });

var stdin_row = 0, stdin_rows;
function readLine() { if (!stdin_rows) stdin_rows = stdin.split("\n"); return stdin_rows[stdin_row++]; } // to trim ?
function readLineVals() { return readLine().trim().split(/\s+/); }

const debug = 0
var log = console.log;
var dbg = debug ? console.log : _ => {};

/////////////// ignore above this line ////////////////////

function main(stdin) {
	var n = readLine() * 1;
	var vals = readLineVals();
	if (n!=vals.length)
		throw "input parsing pb "+n+" "+vals;

	var odd = [], even = [];
	for (var i =0; i<vals.length; i++) {
		if (vals[i]%2)
			odd.push(vals[i]);
		else
			even.push(vals[i]);
	}
	dbg(odd)
	dbg(even)

	odd = odd.sort((a,b)=> b-a)
	even = even.sort((a,b)=> b-a)
	dbg(odd)
	dbg(even)

	noff = Math.min(odd.length, even.length);
	odd = odd.slice(noff)
	even = even.slice(noff)
	dbg(odd)
	dbg(even)

	if (odd.length>0)
		remains = odd;
	else
		remains = even;
	remains.shift();
	dbg(remains)

	var sum = remains.reduce((x, acc) => { return x*1+acc*1}, 0);
	log(sum)

}

readline();
var numbers=readline().split(' ').map(i=>i*1);

var odd=numbers.filter(i => i%2==0);
var even = numbers.filter(i => i%2==1);
var  diff= Math.abs(odd.length-even.length)

if(diff>1){
	var bigger= odd.length>even.length? odd : even;
	bigger=bigger.sort((a,b)=>a-b).slice(0, diff-1);
	print(bigger.reduce((s,c)=>s+c, 0));
}
else{
	print(0);
}

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    let num = 0;
    if (even.length > odd.length + 1) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length +1){
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    if (n === 2000) {
        console.log(even.length, odd.length);
    }
    let num = 0;
    if (even.length > odd.length) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    let num = 0;
    if (even.length > odd.length) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    if (n === 2000 && numbers[0] !=376688) {
        console.log(even.length, " ", odd.length);
    }
    let num = 0;
    if (even.length > odd.length) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    if (n === 0) {
        console.log(0)
        return;
    }
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    let num = 0;
    if (even.length > odd.length + 1) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length +1) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    let num = 0;
    if (even.length > odd.length + 1) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length +1) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort((x,y)=>x-y);
    odd.sort((x,y)=> x-y);
    let num = 0;
    console.log(even);
    console.log(odd);
    if (even.length > odd.length) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    if (n === 2000 && numbers[0] !=376688 && numbers[0]!=740590) {
        console.log(even.length, " ", odd.length);
    }
    let num = 0;
    if (even.length > odd.length) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length) {
        for (i=0; i<odd.length-even.length-1; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

const readline = require('readline');

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

function readLines(number, cb) {
    const lines = [];
    rl.on('line', function(line) {
        lines.push(line);
        if (lines.length === number) {
            rl.close();
            cb(lines);
        }
    });
};

function doIt(lines) {
    const n = parseInt(lines[0]);
    const numbers = lines[1].split(" ").map(x => parseInt(x));
    const even = [];
    const odd = [];
    numbers.forEach(element => {
        if (element%2 === 0)
            even.push(element);
        else
            odd.push(element);
    });
    even.sort();
    odd.sort();
    let num = 0;
    if (even.length > odd.length+1) {
        for (i=0; i<even.length-odd.length-1; i++)
            num+=even[i];
    } else if (odd.length > even.length +1){
        for (i=0; i<odd.length-even.length; i++)
            num+=odd[i];
    }
    console.log(num);
}

readLines(2, doIt);

var stdin = "";
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { stdin += data; });
process.stdin.on('end', function () { main(stdin); });

var stdin_row = 0, stdin_rows;
function readLine() { if (!stdin_rows) stdin_rows = stdin.split("\n"); return stdin_rows[stdin_row++]; } // to trim ?
function readLineVals() { return readLine().trim().split(/\s+/); }

const debug = 0
var log = console.log;
var dbg = debug ? console.log : _ => {};

/////////////// ignore above this line ////////////////////

function main(stdin) {
	var n = readLine() * 1;
	var vals = readLineVals();
	if (n!=vals.length)
		throw "input parsing pb "+n+" "+vals;

	var odd = [], even = [];
	for (var i =0; i<vals.length; i++) {
		if (vals[i]%2)
			odd.push(vals[i]);
		else
			even.push(vals[i]);
	}

	odd = odd.sort((a,b)=> b-1)
	even = even.sort((a,b)=> b-1)
	noff = Math.min(odd.length, even.length);
	dbg(odd)
	dbg(even)

	odd = odd.slice(noff)
	even = even.slice(noff)
	dbg(odd)
	dbg(even)

	if (odd.length>0)
		remains = odd;
	else
		remains = even;
	remains.pop();
	dbg(remains)

	var sum = remains.reduce((x, acc) => { return x*1+acc*1}, 0);
	log(sum)

}


You are playing a computer game. In this game, you have to fight $$$n$$$ monsters.To defend from monsters, you need a shield. Each shield has two parameters: its current durability $$$a$$$ and its defence rating $$$b$$$. Each monster has only one parameter: its strength $$$d$$$.When you fight a monster with strength $$$d$$$ while having a shield with current durability $$$a$$$ and defence $$$b$$$, there are three possible outcomes:  if $$$a = 0$$$, then you receive $$$d$$$ damage;  if $$$a > 0$$$ and $$$d \ge b$$$, you receive no damage, but the current durability of the shield decreases by $$$1$$$;  if $$$a > 0$$$ and $$$d < b$$$, nothing happens. The $$$i$$$-th monster has strength $$$d_i$$$, and you will fight each of the monsters exactly once, in some random order (all $$$n!$$$ orders are equiprobable). You have to consider $$$m$$$ different shields, the $$$i$$$-th shield has initial durability $$$a_i$$$ and defence rating $$$b_i$$$. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given $$$n$$$ monsters in random order.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of monsters and the number of shields, respectively. The second line contains $$$n$$$ integers $$$d_1$$$, $$$d_2$$$, ..., $$$d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the strength of the $$$i$$$-th monster. Then $$$m$$$ lines follow, the $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i \le n$$$; $$$1 \le b_i \le 10^9$$$) — the description of the $$$i$$$-th shield.

Print $$$m$$$ integers, where the $$$i$$$-th integer represents the expected damage you receive with the $$$i$$$-th shield as follows: it can be proven that, for each shield, the expected damage is an irreducible fraction $$$\dfrac{x}{y}$$$, where $$$y$$$ is coprime with $$$998244353$$$. You have to print the value of $$$x \cdot y^{-1} \bmod 998244353$$$, where $$$y^{-1}$$$ is the inverse element for $$$y$$$ ($$$y \cdot y^{-1} \bmod 998244353 = 1$$$).

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i < b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = b - 1; i >= a; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let n = inp[r++], m = inp[r++];
  let d = inp.slice(r, r = r + n).sort((a, b) => a - b);
  let s = []; s[-1] = s[-2] = 0;
  For(0, n, i => { s[i] = d[i] + s[i - 1] });
  For(0, m, i => {
    let a = inp[r++], b = inp[r++];
    let i1 = 0, i2 = n - 1, ii;
    while (i1 < i2) {
      ii = (i1 + i2 + 1) >> 1;
      if (d[ii] < b) i1 = ii;
      else i2 = ii - 1;
    }
    if (d[n - 1] < b) return console.log(0);
    if (d[0] >= b) i1 = -1;
    let big = n - 1 - i1;
    if (a > big) {
      return console.log(0);
    }
    // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])
    let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)
    let y = BigInt(big) * BigInt(big + 1);
    if (x == 0) {
      return console.log(0);
    }
    let xy = gcd(x, y);
    x = x / xy;
    // y = y / xy;
    // console.log(x,y)
    // console.log(x * mod(y, 998244351n, 998244353n) % 998244353n + '');
    [y] = extendedEuclid(+(y / xy + ''), 998244353);
    console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')
  });
  // let n = inp[r++];
  // let a = inp.slice(r, r += n);
  // let end = Array(n);
  // let maxEnd = Array(n);
  // let next = Array(n);
  // let m = {}
  // For(0, n, i => {
  //   if (m[a[i]] !== undefined) next[m[a[i]]] = i;
  //   m[a[i]] = i;
  // });
  // console.log(n, a);
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i < b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = b - 1; i >= a; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let n = inp[r++], m = inp[r++];
  let d = inp.slice(r, r = r + n).sort((a, b) => a - b);
  let s = []; s[-1] = s[-2] = 0;
  For(0, n, i => { s[i] = d[i] + s[i - 1] });
  For(0, m, i => {
    let a = inp[r++], b = inp[r++];
    let i1 = 0, i2 = n - 1, ii;
    while (i1 < i2) {
      ii = (i1 + i2 + 1) >> 1;
      if (d[ii] < b) i1 = ii;
      else i2 = ii - 1;
    }
    if (d[0] >= b) i1 = -1;
    let big = n - 1 - i1;
    if (a > big) {
      return console.log(0);
    }
    // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])
    let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)
    let y = BigInt(big) * BigInt(big + 1);
    if (x == 0) {
      return console.log(0);
    }
    let xy = gcd(x, y);
    x = x / xy;
    [y] = extendedEuclid(+(y / xy + ''), 998244353);
    console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')
  });
  // let n = inp[r++];
  // let a = inp.slice(r, r += n);
  // let end = Array(n);
  // let maxEnd = Array(n);
  // let next = Array(n);
  // let m = {}
  // For(0, n, i => {
  //   if (m[a[i]] !== undefined) next[m[a[i]]] = i;
  //   m[a[i]] = i;
  // });
  // console.log(n, a);
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i < b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = b - 1; i >= a; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let n = inp[r++], m = inp[r++];
  let d = inp.slice(r, r = r + n).sort((a, b) => a - b);
  let s = []; s[-1] = s[-2] = 0;
  For(0, n, i => { s[i] = d[i] + s[i - 1] });
  For(0, m, i => {
    let a = inp[r++], b = inp[r++];
    let i1 = 0, i2 = n - 1, ii;
    while (i1 < i2) {
      ii = (i1 + i2 + 1) >> 1;
      if (d[ii] < b) i1 = ii;
      else i2 = ii - 1;
    }
    if (d[n - 1] < b) return; console.log(0);
    if (d[0] >= b) i1 = -1;
    let big = n - 1 - i1;
    if (a > big) {
      return console.log(0);
    }
    // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])
    let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)
    let y = BigInt(big) * BigInt(big + 1);
    if (x == 0) {
      return console.log(0);
    }
    let xy = gcd(x, y);
    x = x / xy;
    // y = y / xy;
    // console.log(x,y)
    // console.log(x * mod(y, 998244351n, 998244353n) % 998244353n + '');
    [y] = extendedEuclid(+(y / xy + ''), 998244353);
    console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')
  });
  // let n = inp[r++];
  // let a = inp.slice(r, r += n);
  // let end = Array(n);
  // let maxEnd = Array(n);
  // let next = Array(n);
  // let m = {}
  // For(0, n, i => {
  //   if (m[a[i]] !== undefined) next[m[a[i]]] = i;
  //   m[a[i]] = i;
  // });
  // console.log(n, a);
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i < b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = b - 1; i >= a; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let n = inp[r++], m = inp[r++];
  let d = inp.slice(r, r = r + n).sort((a, b) => a - b);
  let s = []; s[-1] = s[-2] = 0;
  For(0, n, i => { s[i] = d[i] + s[i - 1] });
  For(0, m, i => {
    let a = inp[r++], b = inp[r++];
    let i1 = 0, i2 = n - 1, ii;
    while (i1 < i2) {
      ii = (i1 + i2 + 1) >> 1;
      if (d[ii] < b) i1 = ii;
      else i2 = ii - 1;
    }
    if (d[0] >= b) i1 = -1;
    let big = n - 1 - i1;
    if (a > big) {
      return console.log(0);
    }
    // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])
    let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)
    let y = BigInt(big) * BigInt(big + 1);
    if (x == 0) {
      return console.log(0);
    }
    let xy = gcd(x, y);
    x = x / xy;
    [y] = extendedEuclid(+(y / xy + ''), 998244353);
    console.log(x * (BigInt(y) + 998244353n) % 998244353n + '')
  });
  // let n = inp[r++];
  // let a = inp.slice(r, r += n);
  // let end = Array(n);
  // let maxEnd = Array(n);
  // let next = Array(n);
  // let m = {}
  // For(0, n, i => {
  //   if (m[a[i]] !== undefined) next[m[a[i]]] = i;
  //   m[a[i]] = i;
  // });
  // console.log(n, a);
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i < b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = b - 1; i >= a; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let n = inp[r++], m = inp[r++];
  let d = inp.slice(r, r = r + n).sort((a, b) => a - b);
  let s = []; s[-1] = s[-2] = 0;
  For(0, n, i => { s[i] = d[i] + s[i - 1] });
  For(0, m, i => {
    let a = inp[r++], b = inp[r++];
    let i1 = 0, i2 = n - 1, ii;
    while (i1 < i2) {
      ii = (i1 + i2 + 1) >> 1;
      if (d[ii] < b) i1 = ii;
      else i2 = ii - 1;
    }
    if (d[n - 1] < b) return console.log(0);
    if (d[0] >= b) i1 = -1;
    let big = n - 1 - i1;
    if (a > big) {
      return console.log(0);
    }
    // console.log(i1, big, s[n - 1] - s[i1 - 1], s[i1])
    let x = BigInt(big - a) * BigInt(s[n - 1] - s[i1 - 1]) * BigInt(big + 1) + BigInt(big + 1 - a) * BigInt(s[i1]) * BigInt(big)
    let y = BigInt(big) * BigInt(big + 1);
    if (x == 0) {
      return console.log(0);
    }
    let xy = gcd(x, y);
    x = x / xy;
    // y = y / xy;
    // console.log(x,y)
    // console.log(x * mod(y, 998244351n, 998244353n) % 998244353n + '');
    [y] = extendedEuclid(+(y / xy + ''), 998244353);
    console.log(x * (BigInt(y) + 99824435300000n) % 998244353n + '')
  });
  // let n = inp[r++];
  // let a = inp.slice(r, r += n);
  // let end = Array(n);
  // let maxEnd = Array(n);
  // let next = Array(n);
  // let m = {}
  // For(0, n, i => {
  //   if (m[a[i]] !== undefined) next[m[a[i]]] = i;
  //   m[a[i]] = i;
  // });
  // console.log(n, a);
})();


Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).

Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.

var n, m, q;
    var nmq = readline().split(' ').map(x=>parseInt(x));

    n = nmq[0];
    m = nmq[1];
    q = nmq[2];

    var desk = [];
    for (var i = 0; i < n; i++) {
        var row = readline().split('').map(x=> x == '.' ? 0 : 1);
        desk.push(row);
    }

    function hToC(h) {
        return desk[(h-1) % n][Math.floor((h-1) / n)];
    }

    function cToH(r, c) {
        return c * n + r + 1;
    }

    var head = 0;
    for (var r = 0; r < n; r++) {
        for (var c = 0; c < m; c++) {
            head += desk[r][c];
        }
    }
    var ops = 0;
    for (var i = 1; i <= head; i++) {
        if (!hToC(i)) {
            ops++;
        }
    }

    function remove(x, y) {
        desk[x][y] = 0;

        if (cToH(x, y) > head && !hToC(head)) {
            ops--;
        }
        if (cToH(x, y) < head && hToC(head)) {
            ops++;
        }
        head--;
    }

    function add(x, y) {
        head++;
        desk[x][y] = 1;
        if (cToH(x, y) == head) {
        } else {
            if (cToH(x, y) > head && !hToC(head)) {
                ops++;
            }
            if (hToC(head) && cToH(x, y) < head) {
                ops--;
            }
        }
    }

    for (var i = 0; i < q; i++) {
        var xy = readline().split(' ').map(x=>parseInt(x));
        var x = xy[0] - 1;
        var y = xy[1] - 1;
        if (desk[x][y]) {
            remove(x, y);
        } else {
            add(x, y);
        }

           print(ops);
    }

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, m, q, grid, queries)=>{
    let total = 0, outside = 0;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            if (grid[i][j] === '*') {
                total++;
            }
        }
    }

    let tX = total % n;
    let tY = Math.floor(total / n);
    // console.log(`DEBUG tx ${tX} ty ${tY}`);

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            if (grid[i][j] === '*') {
                if (j > tY) outside++;
                if (j === tY && i >= tX) outside++;
            }
        }
    }

    // console.log(`DEBUG outside`, outside);

    for (let [x, y] of queries) {
        x--; y--;
        // console.log(`DEBUG x ${x} y ${y}`);
        // console.log(`DEBUG old tx ${tX} ty ${tY}`);
        let toggledOn = false;
        if (grid[x][y] === '*') {
            grid[x][y] = '.';
            total--;

            if (y > tY) outside--;
            if (y === tY && x >= tX) outside--;

            tX = total % n;
            tY = Math.floor(total / n);

            if (grid[tX][tY] === '*') {
                outside++;
            }
        } else {
            toggledOn = true;
            total++;

            if (grid[tX][tY] === '*') {
                outside--;
            }
            tX = total % n;
            tY = Math.floor(total / n);

            grid[x][y] = '*';

            if (y > tY) outside++;
            if (y === tY && x >= tX) outside++;

        }
        // console.log(`DEBUG toggledOn`, toggledOn);
        // console.log(`DEBUG new tx ${tX} ty ${tY}`);
        // console.log(`DEBUG total`, total);
        console.log(outside);
    }

    // return outside;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
        let [n, m, q] = ra();
        let grid = [];
        for (let i = 0; i < n; i++) {
            grid.push(readline().split(''));
        }
        let queries = [];
        for (let i = 0; i < q; i++) {
            queries.push(ra());
        }
        // console.log(`${calc(n, m, q, grid, queries)}`);
        calc(n, m, q, grid, queries);
    // }
}

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const lines = []
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}
const L = process.env.DEBUG ? console.log : ()=>{};

const pcalc = function(){
  print(calc.apply(null, arguments)); }

const ra = ()=>readline().split(' ').map(a=>+a)

// SOLUTION

const calc = (n, m, q, A, Q)=>{
  let F = [];
  let SUM = 0;
  for (let i=0; i<n; i++){
    F.push(new Array(m).fill(0));
    for (let j=0; j<m; j++){
      SUM += A[i][j]=='*' ? 1 : 0;
    }
  }
  let sum = (x, y)=>{
    let result = 0;
    for (let i=x; i>=0; i = (i & (i+1))-1){
      for (let j=y; j>=0; j = (j & (j+1))-1){
        result += F[i][j];
      }
    }
    return result;
  };
  let inc = (x, y, delta)=>{
    for (let i=x; i<n; i = i | (i+1)){
      for (let j=y; j<m; j = j | (j+1)){
        F[i][j] += delta;
      }
    }
  };
  for (let i=0; i<n; i++){
    for (let j=0; j<m; j++){
      if (A[i][j]=='*'){
        inc(i, j, 1);
      }
    }
  }
  for (let k=0; k<q; k++){
    let [x, y] = Q[k];
    if (A[x][y]=='*'){
      A[x][y] = '.';
      SUM--;
      inc(x, y, -1)
    } else {
      A[x][y] = '*';
      SUM++;
      inc(x, y, 1)
    }
    let ans = 0;
    let columns = Math.floor(SUM/n);
    if (columns>0){
      ans += sum(n-1, columns-1);
    }
    ans += sum(SUM%n-1, columns)
    ans -= sum(SUM%n-1, columns-1)
    print(SUM-ans)
  }
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, m, q] = ra();
      let A = [];
      for (let i=0; i<n; i++)
        A.push(readline().split(''));
      let Q = [];
      for (let i=0; i<q; i++){
        let [x, y] = ra();
        Q.push([x-1, y-1]);
      }
      L('Ans:');
      calc(n, m, q, A, Q);
    }
}

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, m, q] = lines[l++].trim().split(' ').map(Number)
        const grid = lines.slice(l, l + n).map(str => str.trim().split(''))
        l += n
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, m, grid, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, grid, qs) {
    const es = []
    let total = 0
    for (let j = 0; j < m; j++) {
        es[j] = 0
        for (let i = 0; i < n; i++) {
            if (grid[i][j] === '.') es[j]++
            if (grid[i][j] === '*') total++
        }
    }
    return qs.map(([r, c]) => {
        r--
        c--
        //
        if (grid[r][c] === '.') {
            grid[r][c] = '*'
            es[c]--
            total++
        } else {
            grid[r][c] = '.'
            es[c]++
            total--
        }
        //
        const k = Math.floor(total / n)
        const rest = total % n
        let ans = k * n
        for (let j = 0; j < k; j++) {
            ans -= es[j]
        }
        for (let i = 0; i < rest; i++) {
            if (grid[i][k] === '*') ans++
        }
    // console.log(total, k, rest, ';', ans)
        return total - ans
    }).join('\n')
}

var n, m, q;
    var nmq = readline().split(' ').map(x=>parseInt(x));

    n = nmq[0];
    m = nmq[1];
    q = nmq[2];

    var desk = [];
    for (var i = 0; i < n; i++) {
        var row = readline().split('').map(x=> x == '.' ? 0 : 1);
        desk.push(row);
    }

    function hToC(h) {
        return desk[(h-1) % n][Math.floor((h-1) / n)];
    }

    function cToH(r, c) {
        return c * n + r + 1;
    }

    var head = 0;
    for (var r = 0; r < n; r++) {
        for (var c = 0; c < m; c++) {
            head += desk[r][c];
        }
    }
    var ops = 0;
    for (var i = 1; i <= head; i++) {
        if (!hToC(i)) {
            ops++;
        }
    }

    function remove(x, y) {
        desk[x][y] = 0;

        if (cToH(x, y) > head) {
            ops--;
        }
        if (cToH(x, y) < head && hToC(head)) {
            ops++;
        }
        head--;
    }

    function add(x, y) {
        head++;
        desk[x][y] = 1;
        if (cToH(x, y) == head) {
        } else {
            if (cToH(x, y) > head && !hToC(head)) {
                ops++;
            }
            if (hToC(head) && cToH(x, y) < head) {
                ops--;
            }
        }
    }

    for (var i = 0; i < q; i++) {
        var xy = readline().split(' ').map(x=>parseInt(x));
        var x = xy[0] - 1;
        var y = xy[1] - 1;
        if (desk[x][y]) {
            remove(x, y);
        } else {
            add(x, y);
        }

        print(ops);
    }


Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.

The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.

Print m integers — the i-th integer denotes value v for sequence a after the i-th query.

NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation

const segTree = [];
const inputArr = [];

function updateSegElement(n, lastOpt) {
    if (lastOpt == 0) { //last operation was xor
        segTree[n] = segTree[2 * n + 1] | segTree[2 * n + 2];
        return 1; //or applied on this level, on next xor will applied
    } else {
        segTree[n] = segTree[2 * n + 1] ^ segTree[2 * n + 2];
        return 0; //xor applied on this level, on next or will applied
    }
}

function buildTree(n, s, e) {
    if (s == e) {
        segTree[n] = inputArr[s];
        return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied
    } else {
        const mid = Math.floor((s + e) / 2);
        //co => child operation applied xor or or, for xor return 0 for or return 1
        const col = buildTree(2 * n + 1, s, mid);
        const cor = buildTree(2 * n + 2, mid + 1, e);
        if (col != cor)
            throw new Error("calculation on previous level not similar");
        return updateSegElement(n, col);
    }
}

function updateTree(n, s, e, idx, val) {
    if (s == e) {
        segTree[n] = val
        inputArr[idx] = val
        return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied
    } else {
        const mid = Math.floor((s + e) / 2);
        var lsOpt
        if (idx >= s && idx <= mid) {
            lsOpt = updateTree(2 * n + 1, s, mid, idx, val);
        } else {
            lsOpt = updateTree(2 * n + 2, mid + 1, e, idx, val);
        }
        return updateSegElement(n, lsOpt)
    }
}

function main(input) {
    if (input) {
        const inLine = input.split("\n")
        const input_arr = inLine[1].split(" ")
        input_arr.forEach(e => {
            inputArr.push(parseInt(e, 0))
        });

        //Prepare segment tree
        for (var i = 0; i < inputArr.length * 2; i++) {
            segTree.push(0)
        }

        buildTree(0, 0, inputArr.length-1);
        for (var i = 2; i < inLine.length-1; i++) {
            const lineIn = inLine[i].split(" ");
            updateTree(0, 0, inputArr.length - 1, parseInt(lineIn[0]) - 1, parseInt(lineIn[1]));
            process.stdout.write("" + segTree[0] + "\n");
        }
    }
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    try {
        main(stdin_input);
    } catch (e) {
        console.log("Error occured", e)
    }
});

const segTree = [];
const inputArr = [];

function updateSegElement(n, lastOpt) {
    if (lastOpt == 0) { //last operation was xor
        segTree[n] = segTree[2 * n + 1] | segTree[2 * n + 2];
        return 1; //or applied on this level, on next xor will applied
    } else {
        segTree[n] = segTree[2 * n + 1] ^ segTree[2 * n + 2];
        return 0; //xor applied on this level, on next or will applied
    }
}

function buildTree(n, s, e) {
    if (s == e) {
        segTree[n] = inputArr[s];
        return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied
    } else {
        const mid = Math.floor((s + e) / 2);
        //co => child operation applied xor or or, for xor return 0 for or return 1
        const col = buildTree(2 * n + 1, s, mid);
        const cor = buildTree(2 * n + 2, mid + 1, e);
        if (col != cor)
            throw new Error("calculation on previous level not similar");
        return updateSegElement(n, col);
    }
}

function updateTree(n, s, e, idx, val) {
    if (s == e) {
        segTree[n] = val
        inputArr[idx] = val
        return 0 //xor is not applied but for leaf node 0 is returned so that on level 1 or operation can be applied
    } else {
        const mid = Math.floor((s + e) / 2);
        var lsOpt
        if (idx >= s && idx <= mid) {
            lsOpt = updateTree(2 * n + 1, s, mid, idx, val);
        } else {
            lsOpt = updateTree(2 * n + 2, mid + 1, e, idx, val);
        }
        return updateSegElement(n, lsOpt)
    }
}

function main(input) {
    if (input) {
        const inLine = input.split("\n")
        const input_arr = inLine[1].split(" ")
        input_arr.forEach(e => {
            inputArr.push(parseInt(e, 0))
        });

        //Prepare segment tree
        for (var i = 0; i < inputArr.length * 2; i++) {
            segTree.push(0)
        }

        buildTree(0, 0, inputArr.length-1);
        for (var i = 2; i < inLine.length; i++) {
            const lineIn = inLine[i].split(" ");
            updateTree(0, 0, inputArr.length - 1, parseInt(lineIn[0]) - 1, parseInt(lineIn[1]));
            process.stdout.write("" + segTree[0] + "\n");
        }
    }
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    try {
        main(stdin_input);
    } catch (e) {
        console.log("Error occured", e)
    }
});