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, k, x, y, things, g)=>{
    x--; y--;
    let p = new Array(n).fill(-1);

    let visited = new Array(n).fill(false);
    let q = [x];
    while (q.length > 0) {
        let newq = [];
        for (let v of q) {
            if (visited[v]) continue;
            visited[v] = true;
            for (let u of g[v]) {
                if (visited[u]) continue;
                p[u] = v;
                newq.push(u);
            }
        }
        q = newq;
    }

    visited = new Array(n).fill(false);
    visited[x] = true;

    let result = 0;

    if (!visited[y]) {
        let cur = y;
        let count = 0;
        while (!visited[cur]) {
            count++;
            visited[cur] = true;
            cur = p[cur];
        }
        result += count;
    }

    for (let thing of things) {
        thing--;
        if (visited[thing]) continue;

        let cur = thing;
        let count = 0;
        while (!visited[cur]) {
            count++;
            visited[cur] = true;
            cur = p[cur];
        }
        result += 2 * count;
    }

    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        readline();
        // let n = +readline();
        let [n, k] = ra();
        let [x, y] = ra();
        let things = ra();
        let g = new Array(n).fill(0).map(() => new Array());
        for (let i = 0; i < n - 1; i++) {
            let [a, b] = ra();
            g[a - 1].push(b - 1);
            g[b - 1].push(a - 1);
        }
        console.log(`${calc(n, k, x, y, things, g)}`);
    }
}

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

let stackRecursion = (fn, init_state)=>{
  let stack = [];
  let rec = (cb, a0, a1, a2)=>{
    let state = Object.assign({}, init_state);
    stack.push([state, cb, a0, a1, a2]);
  };
  return (cb, a0, a1, a2)=>{
    rec(cb, a0, a1, a2);
    while (stack.length){
      let [state, cb, a0, a1, a2] = stack[stack.length-1];
      let added = false;
      fn((cb, a0, a1, a2)=>{
        added = true;
        rec(cb, a0, a1, a2);
      }, state, a0, a1, a2);
      if (!added){
        cb(state);
        stack.pop();
      }
    }
  };
};

class Graph {
  constructor(){
    this.g = {};
  }
  getAns(x, y, A){
    let G = this.g;
    let dfs = stackRecursion((rec, state, v, avoid1, avoid2)=>{
      let children = G[v]||[];
      if (A.has(v))
        state.itemsCollected++;
      while (state.i<children.length){
        let to = children[state.i++];
        if (to===avoid1 || to===avoid2)
          continue;
        rec(childState=>{
          if (childState.itemsCollected){
            state.itemsCollected += childState.itemsCollected;
            state.timeSpent += 2+childState.timeSpent;
          }
        }, to, v);
        return;
      }
    }, {i: 0, itemsCollected: 0, timeSpent: 0});
    let queue = [], qi = 0;
    queue.push([x, -1]);
    let parent = {};
    let visited = new Set([x]);
    while (qi<queue.length){
      let [v, p] = queue[qi++];
      let children = this.g[v]||[];
      for (let i=0; i<children.length; i++){
        let to = children[i]
        if (to==p || visited.has(to))
          continue;
        parent[to] = v;
        visited.add(to);
        queue.push([to, v]);
      }
    }
    let Y = y;
    let pathXY = [];
    L('Parents', parent)
    while (Y!=x){
      pathXY.push(Y);
      Y = parent[Y];
    }
    pathXY.push(x);
    L('PATH', pathXY, {x, y})
    let minutes = pathXY.length-1;
    for (let i=0; i<pathXY.length; i++){
      dfs(({timeSpent})=>{
        minutes += timeSpent;
      }, pathXY[i], pathXY[i-1], pathXY[i+1]);
    }
    return minutes;
  }
  add(v, u){
    if (!this.g[v])
      this.g[v] = [];
    this.g[v].push(u);
  }
}

const calc = ()=>{
  // READING:
  readline();
  let [n, k] = ra();
  let [x, y] = ra();
  x--; y--;
  let A = new Set(readline().split(' ').map(a=>a-1));
  let G = new Graph();
  for (let i=0; i<n-1; i++){
    let [u, v] = ra();
    u--; v--;
    G.add(u, v)
    G.add(v, u)
  }
  LT({G, A});
  // PROCESSING:
  return G.getAns(x, y, A);
};

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

let wrap = (fn, init_state)=>{
  let stack = [];
  let rec = (cb, a0, a1, a2)=>{
    let state = Object.assign({}, init_state);
    stack.push([state, cb, a0, a1, a2]);
  };
  return (cb, a0, a1, a2)=>{
    rec(cb, a0, a1, a2);
    while (stack.length){
      let [state, cb, a0, a1, a2] = stack[stack.length-1];
      let added = false;
      fn((cb, a0, a1, a2)=>{
        added = true;
        rec(cb, a0, a1, a2);
      }, state, a0, a1, a2);
      if (!added){
        cb(state);
        stack.pop();
      }
    }
  };
};

class Graph {
  constructor(){
    this.g = {};
  }
  getAns(x, y, A){
    let G = this.g;
    let dfs = wrap((rec, state, v, avoid1, avoid2)=>{
      let children = G[v]||[];
      if (A.has(v))
        state.itemsCollected++;
      while (state.i<children.length){
        let to = children[state.i++];
        if (to===avoid1 || to===avoid2)
          continue;
        rec(childState=>{
          if (childState.itemsCollected){
            state.itemsCollected += childState.itemsCollected;
            state.timeSpent += 2+childState.timeSpent;
          }
        }, to, v);
      }
    }, {i: 0, itemsCollected: 0, timeSpent: 0});
    let queue = [], qi = 0;
    queue.push([x, -1]);
    let parent = {};
    let visited = new Set([x]);
    while (qi<queue.length){
      let [v, p] = queue[qi++];
      let children = this.g[v]||[];
      for (let i=0; i<children.length; i++){
        let to = children[i]
        if (to==p || visited.has(to))
          continue;
        parent[to] = v;
        visited.add(to);
        queue.push([to, v]);
      }
    }
    let Y = y;
    let pathXY = [];
    L('Parents', parent)
    while (Y!=x){
      pathXY.push(Y);
      Y = parent[Y];
    }
    pathXY.push(x);
    L('PATH', pathXY, {x, y})
    let minutes = pathXY.length-1;
    for (let i=0; i<pathXY.length; i++){
      dfs(({timeSpent})=>{
        minutes += timeSpent;
      }, pathXY[i], pathXY[i-1], pathXY[i+1]);
    }
    return minutes;
  }
  add(v, u){
    if (!this.g[v])
      this.g[v] = [];
    this.g[v].push(u);
  }
}

const calc = ()=>{
  // READING:
  readline();
  let [n, k] = ra();
  let [x, y] = ra();
  x--; y--;
  let A = new Set(readline().split(' ').map(a=>a-1));
  let G = new Graph();
  for (let i=0; i<n-1; i++){
    let [u, v] = ra();
    u--; v--;
    G.add(u, v)
    G.add(v, u)
  }
  LT({G, A});
  // PROCESSING:
  return G.getAns(x, y, A);
};

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++) {
        l++
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const [x, y] = 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
        output[i] = solve(n, x, y, arr, edges)
    }
    console.log(output.join('\n'))
// })()
})

class Queue {
    constructor() {
        this.map = {}
        this.first = 0
        this.last = -1
    }
    push(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[++this.last] = args[i]
        }
    }
    unshift(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[--this.first] = args[i]
        }
    }
    pop() {
        const r = this.map[this.last]
        delete this.map[this.last]
        this.last--
        return r
    }
    shift() {
        const r = this.map[this.first]
        delete this.map[this.first]
        this.first++
        return r
    }
    get length() {
        if (this.first > this.last) return 0
        return this.last - this.first + 1
    }
    getLast() {
        return this.map[this.last]
    }
}

function solve(n, x, y, arr, edges) {
    const map = arr.reduce((o, u) => {
        o[u] = 1
        return o
    }, {})
    map[y] = 1
// console.log(arr)
    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, x, y, map)
}
function dfs(adj, r, y, map) {
    // const stack = [[r, 0, -1]]
    const stack = new Queue()
    stack.push([r, 0, -1])
    const dp = []
    let dy
    while (stack.length) {
        const [u, i, p] = stack.getLast()// stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            if (u === y) dy = stack.length - 1
        }
        if (i < nb.length) {
            // stack[stack.length - 1]
            stack.getLast()[1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
            dp[u] = 0
            adj[u].forEach(v => {
                if (v === p) return
                if (dp[v] || map[v]) {
                    dp[u] += dp[v] + 2
                }
            })
        }
    }
// console.log(dp, dy)
    return dp[r] - dy
}

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a);
  {
    const queue = [...set],
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push(j);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        res += 2 * dist[i];
        if (p[i] === -1) continue;
        queue.push(p[i]);
      }
      for (let i of queue) {
        if (seta.has(i)) {
          res -= 2 * dist[i];
        } else {
          seta.add(i);
          if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
        }
      }
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (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(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a);
  {
    const queue = [...set].map(num => [num, 0]),
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push([j, dist[j]]);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        queue.push(p[i]);
        res += 2 * dist[i];
      }
      for (let i of queue) {
        if (seta.has(i)) {
          res -= 2 * dist[i];
        } else if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
      }
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (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(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a);
  {
    const queue = [...set].map(num => [num, 0]),
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push([j, dist[j]]);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        queue.push(p[i]);
        res += 2 * dist[i];
      }
      for (let i of queue) {
        if (seta.has(i)) {
          res -= 2 * dist[i];
        }
        if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
      }
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (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(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const seta = new Set(a);
  {
    const st = [];
    const dfs = i => {
      st[i] = 1;
      let res = 0;
      for (let j of g[i]) {
        if (st[j]) continue;
        res += dfs(j);
      }
      if (!set.has(i)) {
        if (res === 0 && seta.has(i)) return 1;
        if (res > 0) return res + 1;
      }
      return res;
    };
    res += dfs(x) * 2;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (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(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a.map(num => num - 1));
  {
    const queue = [...set].map(num => [num, 0]),
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push([j, dist[j]]);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        queue.push(p[i]);
      }
      for (let i of queue) {
        seta.delete(i);
        if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
      }
    }
  }
  for (let i of seta) {
    res += dist[i] * 2;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (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(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [];
  {
    const queue = [...set].map(num => [num, 0]),
          st = [];
    for (let i of set) {
      dist[i] = 0;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
      }
    }
  }
  for (let i of [...new Set(a)].map(num => num - 1)) {
    res += dist[i] * 2;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (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(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();


var readInt = (keys) => {
  var val = readline().split(' ');
  var key = keys.split(', ');
  for (var i = 0; i < key.length; ++i) {
    this[key[i]] = parseInt(val[i]);
  }
};
Array.prototype.init = function (val) {
  var foo = typeof val === 'function' ? val : () => val;
  for (var i = this.length; i--; ) {
    this[i] = foo();
  }
  return this;
};

readInt('N, onTree, offTree');
var edge = new Array(N+1).init(() => []);
for (var i = N-1; i--; ) {
  readInt('u, v');
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star = false;
  edge.forEach(arr => star = star || arr.length === N-1);
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = new Array(N+1).init(0);
  var avail = new Array(N+1).init(2);
  father[1] = null;
  var sa = [1], sb = [], me;
  var bind = (son) => {
    if (father[son] === 0) {
      father[son] = me;
      sa.push(son);
    }
  }
  while (me = sa.pop()) {
    sb.push(me);
    edge[me].forEach(bind);
  }
  var cnt = 0;
  while (me = sb.pop()) {
    if (avail[me] && avail[father[me]]) {
      avail[me]--; avail[father[me]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var temp = readline().split(' ');
var N = parseInt(temp[0]);
var onTree = parseInt(temp[1]);
var offTree = parseInt(temp[2]);
var edge = [];
for (var i = N+1; i--; ) edge.push([]);
var u, v;
for (var i = N-1; i--; ) {
  temp = readline().split(' ');
  u = parseInt(temp[0]);
  v = parseInt(temp[1]);
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star = false;
  for (var i = N; i--; ) {
    if (edge[N-i].length === N-1) {
      star = true;
      break;
    }
  }
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = [], avail = [];
  for (var i = N+1; i--; ) {
    father.push(0);
    avail.push(2);
  }
  father[1] = null;
  var stack = [1], stac2 = [], cnt = 0;
  var node, e;
  while (node = stack.pop()) {
    stac2.push(node);
    e = edge[node];
    tail = true;
    for (var i = e.length; i--; ) {
      if (father[e[i]] === 0) {
        father[e[i]] = node;
        stack.push(e[i]);
        tail = true;
      }
    }
  }
  while (node = stac2.pop()) {
    if (avail[node] && avail[father[node]]) {
      avail[node]--;
      avail[father[node]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var readInt = (keys) => {
  var val = readline().split(' ');
  var key = keys.split(', ');
  for (var i = 0; i < key.length; ++i) {
    this[key[i]] = parseInt(val[i]);
  }
};
Array.prototype.init = function (val) {
  var foo = typeof val === 'function' ? val : () => val;
  for (var i = this.length; i--; ) {
    this[i] = foo();
  }
  return this;
};
readInt('N, onTree, offTree');
var edge = new Array(N+1).init(() => []);
for (var i = N-1; i--; ) {
  readInt('u, v');
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star; edge.forEach(arr => star = arr.length === N-1);
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = new Array(N+1).init(0);
  var avail = new Array(N+1).init(2);
  father[1] = null;
  var sa = [1], sb = [], me;
  var bind = (son) => {
    if (father[son] === 0) {
      father[son] = me;
      sa.push(son);
    }
  }
  while (me = sa.pop()) {
    sb.push(me);
    edge[me].forEach(bind);
  }
  var cnt = 0;
  while (me = sb.pop()) {
    if (avail[me] && avail[father[me]]) {
      avail[me]--; avail[father[me]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var temp = readline().split(' ');
var N = parseInt(temp[0]);
var onTree = parseInt(temp[1]);
var offTree = parseInt(temp[2]);
var edge = [];
for (var i = N+1; i--; ) edge.push([]);
var u, v;
for (var i = N-1; i--; ) {
  temp = readline().split(' ');
  u = parseInt(temp[0]);
  v = parseInt(temp[1]);
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star = false;
  for (var i = N; i--; ) {
    if (edge[N-i].length === N-1) {
      star = true;
      break;
    }
  }
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = [], avail = [];
  for (var i = N+1; i--; ) {
    father.push(0);
    avail.push(2);
  }
  father[1] = null;
  var stack = [1], stac2 = [], cnt = 0;
  var node, e;
  while (node = stack.pop()) {
    stac2.push(node);
    e = edge[node];
    tail = true;
    for (var i = e.length; i--; ) {
      if (father[e[i]] === 0) {
        father[e[i]] = node;
        stack.push(e[i]);
        tail = true;
      }
    }
  }
  while (node = stac2.pop()) {
    if (avail[node] && father[node]) {
      avail[node]--;
      avail[father[node]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var temp = readline().split(' ');
var N = parseInt(temp[0]);
var onTree = parseInt(temp[1]);
var offTree = parseInt(temp[2]);
var edge = [];
for (var i = N+1; i--; ) edge.push([]);
var u, v;
for (var i = N-1; i--; ) {
  temp = readline().split(' ');
  u = parseInt(temp[0]);
  v = parseInt(temp[1]);
  edge[u].push(v);
  edge[v].push(u);
}
var dia = (() => {
  var farthestFrom = (src) => {
    var dis = [];
    for (var i = N+1; i--; ) dis.push(Infinity);
    dis[src] = 0;
    var queue = [src], l = 0;
    queue.pop = () => queue[l++];
    var u, ue, max = 0, maxu = src;
    while (u = queue.pop()) {
      if (dis[u] > max) {
        max = dis[u];
        maxu = u;
      }
      ue = edge[u];
      for (var i = ue.length; i--; ) {
        if (dis[ue[i]] === Infinity) {
          dis[ue[i]] = dis[u] + 1;
          queue.push(ue[i]);
        }
      }
    }
    return {
      dis: max,
      id: maxu
    };
  };
  var memo;
  return () => {
    if (typeof memo !== 'undefined') return memo;
    var u = farthestFrom(1);
    var v = farthestFrom(u.id);
    return memo = v.dis;
  };
})();
if (onTree >= offTree) {
  var centre = false;
  for (var i = N; i--; ) {
    if (edge[N-i].length === N-1) {
      centre = true;
      break;
    }
  }
  print(centre ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  print(dia() * onTree + (N-1-dia()) * offTree);
}


"use strict";

String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

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

for (var i = 0; i < n; i++) {
  var line = readline().getNumArray();
  m.push(line);
}

var x1 = Math.sqrt(m[0][1] * m[1][2] / m[0][2]);
var answ = [];

for (var _i = 0; _i < n; _i++) {
  if (_i == 1) {
    answ.push(x1);
  } else {
    answ.push(m[_i][1] / x1);
  }
}

write(answ.join(' '));

'use strict'

const size = parseInt(readline());
const M0 = readline().split(' ').map(Number);
const M1 = readline().split(' ').map(Number);

const a0 = Math.sqrt(M0[1] * M0[2] / M1[2]);
write(a0 + ' ' + M0.slice(1).map(i => i / a0).join(' '));

process.stdin.resume()
process.stdin.setEncoding('utf8')
let arr = ""
process.stdin.on('data', function(chunk) {
  arr += chunk
});

process.stdin.on('end', () => {
  arr = arr.split('\n')
  const number = parseInt(arr.shift())
  const firstRow = arr[0].split(' ')
  const secondRow = arr[1].split(' ')
  const a1 = Math.sqrt(firstRow[1] * firstRow[2] / secondRow[2])

  process.stdout.write(a1 + ' ')

  for(let i = 1; i < number; i ++){
    process.stdout.write(`${firstRow[i] / a1} `)
  }
  console.log()
})

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
let lineCount = 0, num, multiArr = [];
rl.on('line', function (line) {
    if (lineCount === 0) {
        num = Number(line.trim());
    } else {
        multiArr.push(line.trim().split(' ').map((item) => parseInt(item)));
    }
    if (lineCount === num) {
        console.log(getTable(multiArr));
        rl.close();
    }
    lineCount++;
});

function getTable(multiArr) {
    let len = multiArr.length;
    let resArr = [];
    for (let i = 0; i < len; i++) {
        resArr.push(getMain(i, len));
    }
    return resArr.join(' ');
}

function getMain(i, len) {
    let j, k;
    if (i === 0) {
        j = i + 1, k = i + 2;
    } else if (i === len - 1) {
        j = i - 1, k = i - 2;
    } else {
        j = i - 1; k = i + 1;
    }
    let Mij = multiArr[i][j];
    let Mik = multiArr[i][k];
    let Mjk = multiArr[j][k];
    return Math.sqrt((Mij * Mik) / Mjk);
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
let lineCount = 0, num, multiArr = [];
rl.on('line', function (line) {
    if (lineCount === 0) {
        num = Number(line.trim());
    } else {
        multiArr.push(line.trim().split(' ').map((item) => parseInt(item)));
    }
    if (lineCount === num) {
        console.log(getTable(multiArr));
        rl.close();
    }
    lineCount++;
});

function getTable(multiArr) {
    let len = multiArr.length;
    let resArr = [];

    function getMain(i) {
        let j, k;
        if (i === 0) {
            j = i + 1, k = i + 2;
        } else if (i === len - 1) {
            j = i - 1, k = i - 2;
        } else {
            j = i - 1; k = i + 1;
        }
        let Mij = multiArr[i][j];
        let Mik = multiArr[i][k];
        let Mjk = multiArr[j][k];
        return Math.sqrt((Mij * Mik) / Mjk)
    }

    for (let i = 0; i < len; i++) {
        resArr.push(getMain(i));
    }
    return resArr.join(' ')
}

'use strict'

const size = parseInt(readline());
const M0 = readline().split(' ').map(Number);
const M1 = readline().split(' ').map(Number);

const a0 = Math.sqrt(M0[1] * M0[2] / M1[2]);
write(a0 + M0.slice(1).map(i => i / a0));


function doIt() {
    var fl = readline().split(' ').map(v=>+v);
    var columnsCount = fl[0];
    var height = fl[1];

    var sum = 0, max = 0;
    var map = {};
    var all = readline().split(' ');
    all.forEach(v => {
        if(v in map) {
            map[v] ++;
        } else {
            map[v] = 1;
        }
        if(v > max) max = v;
    });

    var prev = 0, balance = 0;
    Object.keys(map).forEach((v) => {
        sum+=map[v] * v;
        balance += v - prev - map[v];
        if(balance < 0) balance = 0;

        prev = v;
    });

    var remove = sum - balance - all.length;

    print(remove);
}

doIt();

// NYAN NYAN
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
// ░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
// ░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
// ░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
// ░▄▄▄▄▄░░█░░░░░░▀░░░░▀█░░▀▄░░░░░█▀▀░██░░
// ░██▄▀██▄█░░░▄░░░░░░░██░░░░▀▀▀▀▀░░░░██░░
// ░░▀██▄▀██░░░░░░░░▀░██▀░░░░░░░░░░░░░▀██░
// ░░░░▀████░▀░░░░▄░░░██░░░▄█░░░░▄░▄█░░██░
// ░░░░░░░▀█░░░░▄░░░░░██░░░░▄░░░▄░░▄░░░██░
// ░░░░░░░▄█▄░░░░░░░░░░░▀▄░░▀▀▀▀▀▀▀▀░░▄▀░░
// ░░░░░░█▀▀█████████▀▀▀▀████████████▀░░░░
// ░░░░░░████▀░░███▀░░░░░░▀███░░▀██▀░░░░░░
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

// 백준의 노드 버전이 너무 낮아 babel 사용.
// 풀이는 solve() 함수에 있음.

const CODEFORCES_NODE = "cf";
const CODEFORCES_V8 = "cf-v8";
const BEAKJOON = "bj";
const TEST = "test";
// var SITE = BEAKJOON;
var SITE = CODEFORCES_NODE;
var DEBUG = false;

if(SITE == BEAKJOON){
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(search, pos) {
      return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
  }
  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
      if (this_len === undefined || this_len > this.length) {
        this_len = this.length;
      }
      return this.substring(this_len - search.length, this_len) === search;
    };
  }
  if (!String.prototype.repeat) {
    String.prototype.repeat = function(count) {
      'use strict';
      if (this == null) {
        throw new TypeError('can\'t convert ' + this + ' to object');
      }
      var str = '' + this;
      count = +count;
      if (count != count) {
        count = 0;
      }
      if (count < 0) {
        throw new RangeError('repeat count must be non-negative');
      }
      if (count == Infinity) {
        throw new RangeError('repeat count must be less than infinity');
      }
      count = Math.floor(count);
      if (str.length == 0 || count == 0) {
        return '';
      }
      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28) {
        throw new RangeError('repeat count must not overflow maximum string size');
      }
      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
         str += str;
         count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    }
  }
}

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

Function.prototype.repeat = function(times){
  for(let i = 0; i < times; i++){
    this();
  }
}

Array.prototype.getMaxConsecutiveSum = function(defaultValue = -Infinity){
  const N = this.length;
  let maxsum = defaultValue;
  let cursum = defaultValue;
  let cur;
  for(var ii = 0; ii < N; ii++){
    cur = this[ii];
    if(cursum + cur > 0){
      if(cur > cursum + cur){
        cursum = cur;
      } else cursum += cur;
    } else {
      cursum = cur;
      if(maxsum < cursum){
        maxsum = cursum;
      }
    }
    if(maxsum < cursum){
      maxsum = cursum;
    }
  }
  this.maxConsecutiveSum = maxsum;
  return maxsum;
}

try {
  require('manakin').global;
  // require ("babel-polyfill");
} catch (error) {

}
try {
  process.argv.forEach(function (val, index, array) {
    if (val.startsWith("site")) {
      switch (val.split("=")[1]) {
        case "test":
          // console.log('change site to test')
          SITE = TEST;
          break;
        case "cf-node":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf-v8":
          // console.log('change site to cf')
          SITE = CODEFORCES_V8;
          break;
        case "bj":
          // console.log('change site to bj')
          SITE = BEAKJOON;
          break;
      }
    }
    if (val.startsWith("debug")) {
      switch (val.split("=")[1]) {
        case "true":
          DEBUG = true;
          break;
        case "false":
          DEBUG = false;
          break;
      }
    }
  });
} catch (error) {
}

let inputFilePath = '';
switch(SITE){
  case TEST:
    const config = require('config');
    var fs = require("fs");
    var path = require('path');
    inputFilePath = config.get('INPUTFILEPATH') || path.resolve(__dirname, "input.txt");
    break;
  default:
    inputFilePath = './input.txt';
    break;
}
const INPUTFILEPATH = inputFilePath;

// if (!String.prototype.endsWith) {
// 	String.prototype.endsWith = function(search, this_len) {
// 		if (this_len === undefined || this_len > this.length) {
// 			this_len = this.length;
// 		}
// 		return this.substring(this_len - search.length, this_len) === search;
// 	};
// }
// if (!Array.prototype.includes) {
//   Array.prototype.includes = function (target) {
//     return this.indexOf(target) !== -1
//   }
// }

const newLine = '\n';
var ans;
var inputText = "";
var lineCount = 0;
var lines;
var input;
var readline;
var getlines;
var lineOpen = false;
var readingLine = '';

var clockStart;
var clock;

var print;
print = console.log;
var it;
var step;
function EnableLogging(){
  it = console.info;
  step = console.success;
}
function DisableLogging(){
  it = function it(params) {
    return 0;
  }
  step = it;
}
if (DEBUG) {
  EnableLogging();
  clock = function(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
  }
} else {
  DisableLogging();
}

// prepares test data. to replace line input, assign arrays to lines variable.
function prepareTestData() {
  // it(lines);

  // lines = ['custom line 1', 'custom line 2'];
}

// executes exactly once for both test and run. execution time will be included to elapsed time.
const prepareSolve = () => {

}

function power(x, y) {    //분할 정복을 이용하여 x^y 구하기
  let ret = 1;
  while (y > 0) {
    if (y % 2) {
        ret *= x;
        ret %= P;
    }
    x *= x;
    x %= P;
    y /= 2;
  }
  return ret;
}

function createArray(lengths) {
  var arr = new Array(lengths || 0),
    i = lengths;
  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while (i--) arr[lengths - 1 - i] = createArray.apply(this, args);
  }
  return arr;
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ MAIN SOLVE FUNCTION ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function solve(){
  const [n, m] = readInts();
  let maxx = 0;
  // var list = readInts();
  var list = readline().split(' ').map(e=>+e);
  var minn;
  it(list);
  list.sort((a,b)=>a-b);
  it(list);
  it(list);
  maxx = list[list.length-1];
  minn = list[0];
  //1~maxx까지 올라가면서, 비는 경우만이 omit이다. 333 이런경우는 또 omit이 아니다.
  // 그렇다면 333은 결국 123으로 볼 수 있다는 것.
  // 근데 반대로 보는게 맞겠다. 444는 432다.
  // 99955222 -> 98754222
  var newlist = [];
  var last = maxx;

  var needed = 0;
  for(var i=n-1;i >= 0; i--){
    newlist[i] = last;
    last = Math.max(0, Math.min(last-1,list[i-1]));
  }
  it('nl ' + newlist);
  last = 0;
  for(var i=0; i<n;i++){
    needed+=Math.max(1, newlist[i]-last);
    last = newlist[i];
  }
  it('nned ' + needed);

  // it(omittedRightViews);
  var sums = list.reduce((a,b)=>{
    return a+b;
  })
  print(sums- needed);
  // print(sums - (n + omit + minn - 1));
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function resetRead(){
  lineCount = 0;
}

function checkMemoryUsage() {
  it(process.memoryUsage());
}

function readOne(separator=' ') {
  if(lineOpen && readingLine != null){
  // if(lineOpen){
    // it(readingLine);
    let splitPos = readingLine.search(separator)

    let ret = readingLine.slice(0, splitPos);
    if(splitPos == -1){
      // it('close');
      ret = readingLine;
      readingLine = '';
      lineOpen = false;
    }
    readingLine = readingLine.substr(splitPos + 1)
    // it(ret, readingLine, splitPos);
    return ret;
  } else {
    readingLine = readline();
    lineOpen = true;
    if(readingLine == null) return '';
    return readOne(separator);
  }
}

function readInts() {
  try {
    lineOpen = false;
    return readline()
      .split(" ")
      .map(x => parseInt(x));
  } catch (error) {
    console.error(error);
    return null;
  }
}

switch (SITE) {
  case TEST:
    var fs = require("fs");
    var path = require('path');
    // input = fs.createReadStream(path.resolve(__dirname, "input.txt"), {
    //   encoding: "utf8"
    // });
    input = fs.createReadStream(INPUTFILEPATH, {
      encoding: "utf8"
    });

    function inputListener(line) {
      console.log(line);
      if(line.startsWith('end')){
        console.log('end');
        closing();
      }
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;

  case CODEFORCES_NODE:
    input = process.stdin;

    function inputListener(line) {
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;
  case BEAKJOON:
    var fs = require('fs');
    if (DEBUG) {
      // input = fs.readFileSync('./input.txt').toString();
      inputText = fs.readFileSync(INPUTFILEPATH).toString();

    } else {
      inputText = fs.readFileSync('/dev/stdin').toString();
    }

    readline = function () {
      lineCount++;
      let line = lines[lineCount - 1];
      if (line)
        return lines[lineCount - 1].trim();
      else return null;
    }

    getlines = function (inputText) {
      lineCount = 0;
      return inputText.split(/\r?\n/);
    }

    // lines = getlines(input);
    closing();
    break;
  default:
    break;
}

function closing() {
  if(DEBUG){
    DisableLogging();
    const prepareClock = clock();
    lines = getlines(inputText);
    prepareSolve();
    const prepareClockElapsedTime = clock(prepareClock);
    EnableLogging();
    prepareTestData();
    solve();
    resetRead();
    console.warn('performance check');
    DisableLogging();
    clockStart = clock();
    // lines = getlines(inputText);
    solve();
    console.warn(`${clock(clockStart) + prepareClockElapsedTime} ms`);
    EnableLogging();
    process.exit();
  } else {
    lines = getlines(inputText);
    prepareSolve();
    solve();
    process.exit();
  }
}

// NYAN NYAN
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
// ░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
// ░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
// ░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
// ░▄▄▄▄▄░░█░░░░░░▀░░░░▀█░░▀▄░░░░░█▀▀░██░░
// ░██▄▀██▄█░░░▄░░░░░░░██░░░░▀▀▀▀▀░░░░██░░
// ░░▀██▄▀██░░░░░░░░▀░██▀░░░░░░░░░░░░░▀██░
// ░░░░▀████░▀░░░░▄░░░██░░░▄█░░░░▄░▄█░░██░
// ░░░░░░░▀█░░░░▄░░░░░██░░░░▄░░░▄░░▄░░░██░
// ░░░░░░░▄█▄░░░░░░░░░░░▀▄░░▀▀▀▀▀▀▀▀░░▄▀░░
// ░░░░░░█▀▀█████████▀▀▀▀████████████▀░░░░
// ░░░░░░████▀░░███▀░░░░░░▀███░░▀██▀░░░░░░
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

// 백준의 노드 버전이 너무 낮아 babel 사용.
// 풀이는 solve() 함수에 있음.

const CODEFORCES_NODE = "cf";
const CODEFORCES_V8 = "cf-v8";
const BEAKJOON = "bj";
const TEST = "test";
// var SITE = BEAKJOON;
var SITE = CODEFORCES_NODE;
var DEBUG = false;

if(SITE == BEAKJOON){
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(search, pos) {
      return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
  }
  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
      if (this_len === undefined || this_len > this.length) {
        this_len = this.length;
      }
      return this.substring(this_len - search.length, this_len) === search;
    };
  }
  if (!String.prototype.repeat) {
    String.prototype.repeat = function(count) {
      'use strict';
      if (this == null) {
        throw new TypeError('can\'t convert ' + this + ' to object');
      }
      var str = '' + this;
      count = +count;
      if (count != count) {
        count = 0;
      }
      if (count < 0) {
        throw new RangeError('repeat count must be non-negative');
      }
      if (count == Infinity) {
        throw new RangeError('repeat count must be less than infinity');
      }
      count = Math.floor(count);
      if (str.length == 0 || count == 0) {
        return '';
      }
      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28) {
        throw new RangeError('repeat count must not overflow maximum string size');
      }
      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
         str += str;
         count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    }
  }
}

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

Function.prototype.repeat = function(times){
  for(let i = 0; i < times; i++){
    this();
  }
}

Array.prototype.getMaxConsecutiveSum = function(defaultValue = -Infinity){
  const N = this.length;
  let maxsum = defaultValue;
  let cursum = defaultValue;
  let cur;
  for(var ii = 0; ii < N; ii++){
    cur = this[ii];
    if(cursum + cur > 0){
      if(cur > cursum + cur){
        cursum = cur;
      } else cursum += cur;
    } else {
      cursum = cur;
      if(maxsum < cursum){
        maxsum = cursum;
      }
    }
    if(maxsum < cursum){
      maxsum = cursum;
    }
  }
  this.maxConsecutiveSum = maxsum;
  return maxsum;
}

try {
  require('manakin').global;
  // require ("babel-polyfill");
} catch (error) {

}
try {
  process.argv.forEach(function (val, index, array) {
    if (val.startsWith("site")) {
      switch (val.split("=")[1]) {
        case "test":
          // console.log('change site to test')
          SITE = TEST;
          break;
        case "cf-node":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf-v8":
          // console.log('change site to cf')
          SITE = CODEFORCES_V8;
          break;
        case "bj":
          // console.log('change site to bj')
          SITE = BEAKJOON;
          break;
      }
    }
    if (val.startsWith("debug")) {
      switch (val.split("=")[1]) {
        case "true":
          DEBUG = true;
          break;
        case "false":
          DEBUG = false;
          break;
      }
    }
  });
} catch (error) {
}

let inputFilePath = '';
switch(SITE){
  case TEST:
    const config = require('config');
    var fs = require("fs");
    var path = require('path');
    inputFilePath = config.get('INPUTFILEPATH') || path.resolve(__dirname, "input.txt");
    break;
  default:
    inputFilePath = './input.txt';
    break;
}
const INPUTFILEPATH = inputFilePath;

// if (!String.prototype.endsWith) {
// 	String.prototype.endsWith = function(search, this_len) {
// 		if (this_len === undefined || this_len > this.length) {
// 			this_len = this.length;
// 		}
// 		return this.substring(this_len - search.length, this_len) === search;
// 	};
// }
// if (!Array.prototype.includes) {
//   Array.prototype.includes = function (target) {
//     return this.indexOf(target) !== -1
//   }
// }

const newLine = '\n';
var ans;
var inputText = "";
var lineCount = 0;
var lines;
var input;
var readline;
var getlines;
var lineOpen = false;
var readingLine = '';

var clockStart;
var clock;

var print;
print = console.log;
var it;
var step;
function EnableLogging(){
  it = console.info;
  step = console.success;
}
function DisableLogging(){
  it = function it(params) {
    return 0;
  }
  step = it;
}
if (DEBUG) {
  EnableLogging();
  clock = function(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
  }
} else {
  DisableLogging();
}

// prepares test data. to replace line input, assign arrays to lines variable.
function prepareTestData() {
  // it(lines);

  // lines = ['custom line 1', 'custom line 2'];
}

// executes exactly once for both test and run. execution time will be included to elapsed time.
const prepareSolve = () => {

}

function power(x, y) {    //분할 정복을 이용하여 x^y 구하기
  let ret = 1;
  while (y > 0) {
    if (y % 2) {
        ret *= x;
        ret %= P;
    }
    x *= x;
    x %= P;
    y /= 2;
  }
  return ret;
}

function createArray(lengths) {
  var arr = new Array(lengths || 0),
    i = lengths;
  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while (i--) arr[lengths - 1 - i] = createArray.apply(this, args);
  }
  return arr;
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ MAIN SOLVE FUNCTION ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function solve(){
  const [n, m] = readInts();
  let maxx = 0;
  var list = readInts();
  var minn;
  it(list);
  list.sort();
  it(list);
  maxx = list[list.length-1];
  minn = list[0];
  //1~maxx까지 올라가면서, 비는 경우만이 omit이다. 333 이런경우는 또 omit이 아니다.
  // 그렇다면 333은 결국 123으로 볼 수 있다는 것.
  // 근데 반대로 보는게 맞겠다. 444는 432다.
  //
  var newlist = [];
  var last = maxx;

  var needed = 0;
  for(var i=n-1;i >= 0; i--){
    newlist[i] = last;
    last = Math.max(0, Math.min(last-1,list[i-1]));
  }
  it('nl ' + newlist);
  last = 0;
  for(var i=0; i<n;i++){
    needed+=Math.max(1, newlist[i]-last);
    last = newlist[i];
  }
  it('nned ' + needed);

  // it(omittedRightViews);
  var sums = list.reduce((a,b)=>{
    return a+b;
  })
  print(sums- needed);
  // print(sums - (n + omit + minn - 1));
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function resetRead(){
  lineCount = 0;
}

function checkMemoryUsage() {
  it(process.memoryUsage());
}

function readOne(separator=' ') {
  if(lineOpen && readingLine != null){
  // if(lineOpen){
    // it(readingLine);
    let splitPos = readingLine.search(separator)

    let ret = readingLine.slice(0, splitPos);
    if(splitPos == -1){
      // it('close');
      ret = readingLine;
      readingLine = '';
      lineOpen = false;
    }
    readingLine = readingLine.substr(splitPos + 1)
    // it(ret, readingLine, splitPos);
    return ret;
  } else {
    readingLine = readline();
    lineOpen = true;
    if(readingLine == null) return '';
    return readOne(separator);
  }
}

function readInts() {
  try {
    lineOpen = false;
    return readline()
      .split(" ")
      .map(x => parseInt(x));
  } catch (error) {
    console.error(error);
    return null;
  }
}

switch (SITE) {
  case TEST:
    var fs = require("fs");
    var path = require('path');
    // input = fs.createReadStream(path.resolve(__dirname, "input.txt"), {
    //   encoding: "utf8"
    // });
    input = fs.createReadStream(INPUTFILEPATH, {
      encoding: "utf8"
    });

    function inputListener(line) {
      console.log(line);
      if(line.startsWith('end')){
        console.log('end');
        closing();
      }
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;

  case CODEFORCES_NODE:
    input = process.stdin;

    function inputListener(line) {
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;
  case BEAKJOON:
    var fs = require('fs');
    if (DEBUG) {
      // input = fs.readFileSync('./input.txt').toString();
      inputText = fs.readFileSync(INPUTFILEPATH).toString();

    } else {
      inputText = fs.readFileSync('/dev/stdin').toString();
    }

    readline = function () {
      lineCount++;
      let line = lines[lineCount - 1];
      if (line)
        return lines[lineCount - 1].trim();
      else return null;
    }

    getlines = function (inputText) {
      lineCount = 0;
      return inputText.split(/\r?\n/);
    }

    // lines = getlines(input);
    closing();
    break;
  default:
    break;
}

function closing() {
  if(DEBUG){
    DisableLogging();
    const prepareClock = clock();
    lines = getlines(inputText);
    prepareSolve();
    const prepareClockElapsedTime = clock(prepareClock);
    EnableLogging();
    prepareTestData();
    solve();
    resetRead();
    console.warn('performance check');
    DisableLogging();
    clockStart = clock();
    // lines = getlines(inputText);
    solve();
    console.warn(`${clock(clockStart) + prepareClockElapsedTime} ms`);
    EnableLogging();
    process.exit();
  } else {
    lines = getlines(inputText);
    prepareSolve();
    solve();
    process.exit();
  }
}

// NYAN NYAN
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
// ░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
// ░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
// ░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
// ░▄▄▄▄▄░░█░░░░░░▀░░░░▀█░░▀▄░░░░░█▀▀░██░░
// ░██▄▀██▄█░░░▄░░░░░░░██░░░░▀▀▀▀▀░░░░██░░
// ░░▀██▄▀██░░░░░░░░▀░██▀░░░░░░░░░░░░░▀██░
// ░░░░▀████░▀░░░░▄░░░██░░░▄█░░░░▄░▄█░░██░
// ░░░░░░░▀█░░░░▄░░░░░██░░░░▄░░░▄░░▄░░░██░
// ░░░░░░░▄█▄░░░░░░░░░░░▀▄░░▀▀▀▀▀▀▀▀░░▄▀░░
// ░░░░░░█▀▀█████████▀▀▀▀████████████▀░░░░
// ░░░░░░████▀░░███▀░░░░░░▀███░░▀██▀░░░░░░
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

// 백준의 노드 버전이 너무 낮아 babel 사용.
// 풀이는 solve() 함수에 있음.

const CODEFORCES_NODE = "cf";
const CODEFORCES_V8 = "cf-v8";
const BEAKJOON = "bj";
const TEST = "test";
// var SITE = BEAKJOON;
var SITE = CODEFORCES_NODE;
var DEBUG = false;

if(SITE == BEAKJOON){
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(search, pos) {
      return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
  }
  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
      if (this_len === undefined || this_len > this.length) {
        this_len = this.length;
      }
      return this.substring(this_len - search.length, this_len) === search;
    };
  }
  if (!String.prototype.repeat) {
    String.prototype.repeat = function(count) {
      'use strict';
      if (this == null) {
        throw new TypeError('can\'t convert ' + this + ' to object');
      }
      var str = '' + this;
      count = +count;
      if (count != count) {
        count = 0;
      }
      if (count < 0) {
        throw new RangeError('repeat count must be non-negative');
      }
      if (count == Infinity) {
        throw new RangeError('repeat count must be less than infinity');
      }
      count = Math.floor(count);
      if (str.length == 0 || count == 0) {
        return '';
      }
      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28) {
        throw new RangeError('repeat count must not overflow maximum string size');
      }
      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
         str += str;
         count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    }
  }
}

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

Function.prototype.repeat = function(times){
  for(let i = 0; i < times; i++){
    this();
  }
}

Array.prototype.getMaxConsecutiveSum = function(defaultValue = -Infinity){
  const N = this.length;
  let maxsum = defaultValue;
  let cursum = defaultValue;
  let cur;
  for(var ii = 0; ii < N; ii++){
    cur = this[ii];
    if(cursum + cur > 0){
      if(cur > cursum + cur){
        cursum = cur;
      } else cursum += cur;
    } else {
      cursum = cur;
      if(maxsum < cursum){
        maxsum = cursum;
      }
    }
    if(maxsum < cursum){
      maxsum = cursum;
    }
  }
  this.maxConsecutiveSum = maxsum;
  return maxsum;
}

try {
  require('manakin').global;
  // require ("babel-polyfill");
} catch (error) {

}
try {
  process.argv.forEach(function (val, index, array) {
    if (val.startsWith("site")) {
      switch (val.split("=")[1]) {
        case "test":
          // console.log('change site to test')
          SITE = TEST;
          break;
        case "cf-node":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf-v8":
          // console.log('change site to cf')
          SITE = CODEFORCES_V8;
          break;
        case "bj":
          // console.log('change site to bj')
          SITE = BEAKJOON;
          break;
      }
    }
    if (val.startsWith("debug")) {
      switch (val.split("=")[1]) {
        case "true":
          DEBUG = true;
          break;
        case "false":
          DEBUG = false;
          break;
      }
    }
  });
} catch (error) {
}

let inputFilePath = '';
switch(SITE){
  case TEST:
    const config = require('config');
    var fs = require("fs");
    var path = require('path');
    inputFilePath = config.get('INPUTFILEPATH') || path.resolve(__dirname, "input.txt");
    break;
  default:
    inputFilePath = './input.txt';
    break;
}
const INPUTFILEPATH = inputFilePath;

// if (!String.prototype.endsWith) {
// 	String.prototype.endsWith = function(search, this_len) {
// 		if (this_len === undefined || this_len > this.length) {
// 			this_len = this.length;
// 		}
// 		return this.substring(this_len - search.length, this_len) === search;
// 	};
// }
// if (!Array.prototype.includes) {
//   Array.prototype.includes = function (target) {
//     return this.indexOf(target) !== -1
//   }
// }

const newLine = '\n';
var ans;
var inputText = "";
var lineCount = 0;
var lines;
var input;
var readline;
var getlines;
var lineOpen = false;
var readingLine = '';

var clockStart;
var clock;

var print;
print = console.log;
var it;
var step;
function EnableLogging(){
  it = console.info;
  step = console.success;
}
function DisableLogging(){
  it = function it(params) {
    return 0;
  }
  step = it;
}
if (DEBUG) {
  EnableLogging();
  clock = function(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
  }
} else {
  DisableLogging();
}

// prepares test data. to replace line input, assign arrays to lines variable.
function prepareTestData() {
  // it(lines);

  // lines = ['custom line 1', 'custom line 2'];
}

// executes exactly once for both test and run. execution time will be included to elapsed time.
const prepareSolve = () => {

}

function power(x, y) {    //분할 정복을 이용하여 x^y 구하기
  let ret = 1;
  while (y > 0) {
    if (y % 2) {
        ret *= x;
        ret %= P;
    }
    x *= x;
    x %= P;
    y /= 2;
  }
  return ret;
}

function createArray(lengths) {
  var arr = new Array(lengths || 0),
    i = lengths;
  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while (i--) arr[lengths - 1 - i] = createArray.apply(this, args);
  }
  return arr;
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ MAIN SOLVE FUNCTION ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function solve(){
  const [n, m] = readInts();
  let maxx = 0;
  var list = readInts();

  it(list);
  list.sort();
  it(list);
  maxx = list[list.length - 1];
  //1~maxx까지 올라가면서, 비는 경우만이 omit이다. 333 이런경우는 또 omit이 아니다.
  // 그렇다면 333은 결국 123으로 볼 수 있다는 것.
  var checked = [];
  var checked2 = [];
  var omittedRightViews = [];
  var omit = 0;
  for(var i=1;i<=maxx;i++){
    it(list[i-1], i);
    if(list[i-1] < i || list[i-1] == undefined)
      omit++;
  }
  // it(omittedRightViews);
  var sums = list.reduce((a,b)=>{
    return a+b;
  })
  it(sums)
  it(omit);
  print(sums - (n + omit));
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function resetRead(){
  lineCount = 0;
}

function checkMemoryUsage() {
  it(process.memoryUsage());
}

function readOne(separator=' ') {
  if(lineOpen && readingLine != null){
  // if(lineOpen){
    // it(readingLine);
    let splitPos = readingLine.search(separator)

    let ret = readingLine.slice(0, splitPos);
    if(splitPos == -1){
      // it('close');
      ret = readingLine;
      readingLine = '';
      lineOpen = false;
    }
    readingLine = readingLine.substr(splitPos + 1)
    // it(ret, readingLine, splitPos);
    return ret;
  } else {
    readingLine = readline();
    lineOpen = true;
    if(readingLine == null) return '';
    return readOne(separator);
  }
}

function readInts() {
  try {
    lineOpen = false;
    return readline()
      .split(" ")
      .map(x => parseInt(x));
  } catch (error) {
    console.error(error);
    return null;
  }
}

switch (SITE) {
  case TEST:
    var fs = require("fs");
    var path = require('path');
    // input = fs.createReadStream(path.resolve(__dirname, "input.txt"), {
    //   encoding: "utf8"
    // });
    input = fs.createReadStream(INPUTFILEPATH, {
      encoding: "utf8"
    });

    function inputListener(line) {
      console.log(line);
      if(line.startsWith('end')){
        console.log('end');
        closing();
      }
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;

  case CODEFORCES_NODE:
    input = process.stdin;

    function inputListener(line) {
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;
  case BEAKJOON:
    var fs = require('fs');
    if (DEBUG) {
      // input = fs.readFileSync('./input.txt').toString();
      inputText = fs.readFileSync(INPUTFILEPATH).toString();

    } else {
      inputText = fs.readFileSync('/dev/stdin').toString();
    }

    readline = function () {
      lineCount++;
      let line = lines[lineCount - 1];
      if (line)
        return lines[lineCount - 1].trim();
      else return null;
    }

    getlines = function (inputText) {
      lineCount = 0;
      return inputText.split(/\r?\n/);
    }

    // lines = getlines(input);
    closing();
    break;
  default:
    break;
}

function closing() {
  if(DEBUG){
    DisableLogging();
    const prepareClock = clock();
    lines = getlines(inputText);
    prepareSolve();
    const prepareClockElapsedTime = clock(prepareClock);
    EnableLogging();
    prepareTestData();
    solve();
    resetRead();
    console.warn('performance check');
    DisableLogging();
    clockStart = clock();
    // lines = getlines(inputText);
    solve();
    console.warn(`${clock(clockStart) + prepareClockElapsedTime} ms`);
    EnableLogging();
    process.exit();
  } else {
    lines = getlines(inputText);
    prepareSolve();
    solve();
    process.exit();
  }
}

// NYAN NYAN
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
// ░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
// ░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
// ░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
// ░▄▄▄▄▄░░█░░░░░░▀░░░░▀█░░▀▄░░░░░█▀▀░██░░
// ░██▄▀██▄█░░░▄░░░░░░░██░░░░▀▀▀▀▀░░░░██░░
// ░░▀██▄▀██░░░░░░░░▀░██▀░░░░░░░░░░░░░▀██░
// ░░░░▀████░▀░░░░▄░░░██░░░▄█░░░░▄░▄█░░██░
// ░░░░░░░▀█░░░░▄░░░░░██░░░░▄░░░▄░░▄░░░██░
// ░░░░░░░▄█▄░░░░░░░░░░░▀▄░░▀▀▀▀▀▀▀▀░░▄▀░░
// ░░░░░░█▀▀█████████▀▀▀▀████████████▀░░░░
// ░░░░░░████▀░░███▀░░░░░░▀███░░▀██▀░░░░░░
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

// 백준의 노드 버전이 너무 낮아 babel 사용.
// 풀이는 solve() 함수에 있음.

const CODEFORCES_NODE = "cf";
const CODEFORCES_V8 = "cf-v8";
const BEAKJOON = "bj";
const TEST = "test";
// var SITE = BEAKJOON;
var SITE = CODEFORCES_NODE;
var DEBUG = false;

if(SITE == BEAKJOON){
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(search, pos) {
      return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
  }
  if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
      if (this_len === undefined || this_len > this.length) {
        this_len = this.length;
      }
      return this.substring(this_len - search.length, this_len) === search;
    };
  }
  if (!String.prototype.repeat) {
    String.prototype.repeat = function(count) {
      'use strict';
      if (this == null) {
        throw new TypeError('can\'t convert ' + this + ' to object');
      }
      var str = '' + this;
      count = +count;
      if (count != count) {
        count = 0;
      }
      if (count < 0) {
        throw new RangeError('repeat count must be non-negative');
      }
      if (count == Infinity) {
        throw new RangeError('repeat count must be less than infinity');
      }
      count = Math.floor(count);
      if (str.length == 0 || count == 0) {
        return '';
      }
      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28) {
        throw new RangeError('repeat count must not overflow maximum string size');
      }
      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
         str += str;
         count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    }
  }
}

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

Function.prototype.repeat = function(times){
  for(let i = 0; i < times; i++){
    this();
  }
}

Array.prototype.getMaxConsecutiveSum = function(defaultValue = -Infinity){
  const N = this.length;
  let maxsum = defaultValue;
  let cursum = defaultValue;
  let cur;
  for(var ii = 0; ii < N; ii++){
    cur = this[ii];
    if(cursum + cur > 0){
      if(cur > cursum + cur){
        cursum = cur;
      } else cursum += cur;
    } else {
      cursum = cur;
      if(maxsum < cursum){
        maxsum = cursum;
      }
    }
    if(maxsum < cursum){
      maxsum = cursum;
    }
  }
  this.maxConsecutiveSum = maxsum;
  return maxsum;
}

try {
  require('manakin').global;
  // require ("babel-polyfill");
} catch (error) {

}
try {
  process.argv.forEach(function (val, index, array) {
    if (val.startsWith("site")) {
      switch (val.split("=")[1]) {
        case "test":
          // console.log('change site to test')
          SITE = TEST;
          break;
        case "cf-node":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf":
          // console.log('change site to cf')
          SITE = CODEFORCES_NODE;
          break;
        case "cf-v8":
          // console.log('change site to cf')
          SITE = CODEFORCES_V8;
          break;
        case "bj":
          // console.log('change site to bj')
          SITE = BEAKJOON;
          break;
      }
    }
    if (val.startsWith("debug")) {
      switch (val.split("=")[1]) {
        case "true":
          DEBUG = true;
          break;
        case "false":
          DEBUG = false;
          break;
      }
    }
  });
} catch (error) {
}

let inputFilePath = '';
switch(SITE){
  case TEST:
    const config = require('config');
    var fs = require("fs");
    var path = require('path');
    inputFilePath = config.get('INPUTFILEPATH') || path.resolve(__dirname, "input.txt");
    break;
  default:
    inputFilePath = './input.txt';
    break;
}
const INPUTFILEPATH = inputFilePath;

// if (!String.prototype.endsWith) {
// 	String.prototype.endsWith = function(search, this_len) {
// 		if (this_len === undefined || this_len > this.length) {
// 			this_len = this.length;
// 		}
// 		return this.substring(this_len - search.length, this_len) === search;
// 	};
// }
// if (!Array.prototype.includes) {
//   Array.prototype.includes = function (target) {
//     return this.indexOf(target) !== -1
//   }
// }

const newLine = '\n';
var ans;
var inputText = "";
var lineCount = 0;
var lines;
var input;
var readline;
var getlines;
var lineOpen = false;
var readingLine = '';

var clockStart;
var clock;

var print;
print = console.log;
var it;
var step;
function EnableLogging(){
  it = console.info;
  step = console.success;
}
function DisableLogging(){
  it = function it(params) {
    return 0;
  }
  step = it;
}
if (DEBUG) {
  EnableLogging();
  clock = function(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
  }
} else {
  DisableLogging();
}

// prepares test data. to replace line input, assign arrays to lines variable.
function prepareTestData() {
  // it(lines);

  // lines = ['custom line 1', 'custom line 2'];
}

// executes exactly once for both test and run. execution time will be included to elapsed time.
const prepareSolve = () => {

}

function power(x, y) {    //분할 정복을 이용하여 x^y 구하기
  let ret = 1;
  while (y > 0) {
    if (y % 2) {
        ret *= x;
        ret %= P;
    }
    x *= x;
    x %= P;
    y /= 2;
  }
  return ret;
}

function createArray(lengths) {
  var arr = new Array(lengths || 0),
    i = lengths;
  if (arguments.length > 1) {
    var args = Array.prototype.slice.call(arguments, 1);
    while (i--) arr[lengths - 1 - i] = createArray.apply(this, args);
  }
  return arr;
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ MAIN SOLVE FUNCTION ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function solve(){
  const [n, m] = readInts();
  let maxx = 0;
  var list = readInts();
  var minn;
  it(list);
  list.sort();
  it(list);
  maxx = list[list.length-1];
  minn = list[0];
  //1~maxx까지 올라가면서, 비는 경우만이 omit이다. 333 이런경우는 또 omit이 아니다.
  // 그렇다면 333은 결국 123으로 볼 수 있다는 것.
  // 근데 반대로 보는게 맞겠다. 444는 432다.
  //
  var newlist = [];
  var last = maxx;

  var needed = 0;
  for(var i=n-1;i >= 0; i--){
    newlist[i] = last;
    last = Math.max(0, Math.min(last-1,list[i-1]));
  }
  it('nl ' + newlist);
  last = 0;
  for(var i=0; i<n;i++){
    needed+=Math.max(1, newlist[i]-last);
    last = newlist[i];
  }
  it('nned ' + needed);

  // it(omittedRightViews);
  var sums = list.reduce((a,b)=>{
    return a+b;
  })
  it(sums- needed);
  // print(sums - (n + omit + minn - 1));
}

// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

function resetRead(){
  lineCount = 0;
}

function checkMemoryUsage() {
  it(process.memoryUsage());
}

function readOne(separator=' ') {
  if(lineOpen && readingLine != null){
  // if(lineOpen){
    // it(readingLine);
    let splitPos = readingLine.search(separator)

    let ret = readingLine.slice(0, splitPos);
    if(splitPos == -1){
      // it('close');
      ret = readingLine;
      readingLine = '';
      lineOpen = false;
    }
    readingLine = readingLine.substr(splitPos + 1)
    // it(ret, readingLine, splitPos);
    return ret;
  } else {
    readingLine = readline();
    lineOpen = true;
    if(readingLine == null) return '';
    return readOne(separator);
  }
}

function readInts() {
  try {
    lineOpen = false;
    return readline()
      .split(" ")
      .map(x => parseInt(x));
  } catch (error) {
    console.error(error);
    return null;
  }
}

switch (SITE) {
  case TEST:
    var fs = require("fs");
    var path = require('path');
    // input = fs.createReadStream(path.resolve(__dirname, "input.txt"), {
    //   encoding: "utf8"
    // });
    input = fs.createReadStream(INPUTFILEPATH, {
      encoding: "utf8"
    });

    function inputListener(line) {
      console.log(line);
      if(line.startsWith('end')){
        console.log('end');
        closing();
      }
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;

  case CODEFORCES_NODE:
    input = process.stdin;

    function inputListener(line) {
      if (!line) {
        closing();
      }
      lineCount++;
      inputText += line + "\r\n";
    }

    function readlines() {
      const readline = require("readline");
      const rl = readline.createInterface({
        input,
        output: process.stdout,
        terminal: false
      });
      rl.on("line", inputListener);
      rl.on('close', closing);
    }

    getlines = function* (inputText) {
      var lines = inputText.split(/\r?\n/);
      for (let line of lines) {
        yield line + newLine;
      }
    }

    readline = function () {
      return lines.next().value.trim();
    }

    readlines();

    break;
  case BEAKJOON:
    var fs = require('fs');
    if (DEBUG) {
      // input = fs.readFileSync('./input.txt').toString();
      inputText = fs.readFileSync(INPUTFILEPATH).toString();

    } else {
      inputText = fs.readFileSync('/dev/stdin').toString();
    }

    readline = function () {
      lineCount++;
      let line = lines[lineCount - 1];
      if (line)
        return lines[lineCount - 1].trim();
      else return null;
    }

    getlines = function (inputText) {
      lineCount = 0;
      return inputText.split(/\r?\n/);
    }

    // lines = getlines(input);
    closing();
    break;
  default:
    break;
}

function closing() {
  if(DEBUG){
    DisableLogging();
    const prepareClock = clock();
    lines = getlines(inputText);
    prepareSolve();
    const prepareClockElapsedTime = clock(prepareClock);
    EnableLogging();
    prepareTestData();
    solve();
    resetRead();
    console.warn('performance check');
    DisableLogging();
    clockStart = clock();
    // lines = getlines(inputText);
    solve();
    console.warn(`${clock(clockStart) + prepareClockElapsedTime} ms`);
    EnableLogging();
    process.exit();
  } else {
    lines = getlines(inputText);
    prepareSolve();
    solve();
    process.exit();
  }
}


var parseIntFunc = function(x) { return parseInt(x); };
var numbers = readline().split(" ").map(parseIntFunc);
var n = numbers[0];
var k = numbers[1];
var q = numbers[2];

var friends = readline().split(" ").map(parseIntFunc);
var friendsOnlineSorted = [];
var friendsOnline = [];

var binarySearch = function (searchElement) {
	var minIndex = 0;
	var maxIndex = this.length - 1;
	var currentIndex;
	var currentElement;
	while (minIndex <= maxIndex) {
		currentIndex = (minIndex + maxIndex) / 2 | 0;
		currentElement = this[currentIndex];

		if (currentElement > searchElement) {
			minIndex = currentIndex + 1;
		}
		else if (currentElement < searchElement) {
			maxIndex = currentIndex - 1;
		}
		else {
			return currentIndex;
		}
	}
	return minIndex;
};

for (var i = 0; i < q; i++){
    var query = readline().split(" ").map(parseIntFunc);
    var friend = query[1] - 1;
    var friendValue = friends[friend];
    var queryType = query[0];
    if (queryType === 2){
        if (friendsOnline[friend]){
            if (binarySearch.call(friendsOnlineSorted, friendValue) < k){
                print('YES');
            } else {
                print('NO');
            }
        } else {
            print('NO');
        }
    } else {
        friendsOnlineSorted.splice(binarySearch.call(friendsOnlineSorted, friendValue),0,friendValue);
        friendsOnline[friend] = 1;
    }
}

var line1 = readline().split(' ').map(Number);
var n = line1[0];
var k = line1[1];
var q = line1[2];

var t = readline().split(' ').map(Number);

var requests = [];

var buffer = [];

for(var i = 0; i < q; i++){
  var req = readline().split(' ').map(Number);
  if(req[0] === 1){
    // Add friend to the buffer
    var ti = t[req[1] - 1];
    var inserted = false;
    for(var j = 0; j < buffer.length; j++){
      if(buffer[j].t < ti){
        buffer.splice(j, 0, {id: req[1], t: ti});
        inserted = true;
        break;
      }
    }

    if(inserted === false){
      buffer.splice(j, 0, {id: req[1], t: ti});
    }

    if(buffer.length > k){
      buffer = buffer.slice(0, k);
    }
  }
  if(req[0] === 2){
    // Validate if Online
    var found = false;
    for(var u = 0; u < Math.min(k, buffer.length); u++){
      if(buffer[u].id === req[1]){
        found = true;
        break;
      }
    }

    if(found === true){
      print("YES");
    } else {
      print("NO");
    }
  }
}

/*
4 2 8\n300 950 500 200\n1 3\n2 4\n2 3\n1 1\n1 2\n2 1\n2 2\n2 3\n
*/

var parseIntFunc = function(x) { return parseInt(x); };
var numbers = readline().split(" ").map(parseIntFunc);
var n = numbers[0];
var k = numbers[1];
var q = numbers[2];

var friends = readline().split(" ").map(parseIntFunc);
var friendsOnlineSorted = [];
var friendsOnline = [];

var binarySearch = function (searchElement) {
	var minIndex = 0;
	var maxIndex = this.length - 1;
	var currentIndex;
	var currentElement;
	while (minIndex <= maxIndex) {
		currentIndex = (minIndex + maxIndex) / 2 | 0;
		currentElement = this[currentIndex];

		if (currentElement > searchElement) {
			minIndex = currentIndex + 1;
		}
		else if (currentElement < searchElement) {
			maxIndex = currentIndex - 1;
		}
		else {
			return currentIndex;
		}
	}
	return minIndex;
};

for (var i = 0; i < q; i++){
    var query = readline().split(" ").map(parseIntFunc);
    var friend = query[1] - 1;
    var friendValue = friends[friend];
    var queryType = query[0];
    if (queryType === 2){
        if (friendsOnline[friend]){
            if (binarySearch.call(friendsOnlineSorted, friendValue) < k){
                print('Yes');
            } else {
                print('No');
            }
        } else {
            print('No');
        }
    } else {
        friendsOnlineSorted.splice(binarySearch.call(friendsOnlineSorted, friendValue),0,friendValue);
        friendsOnline[friend] = 1;
    }
}


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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 1e6;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rl();
		const b = rl();

		const cnt = [[0, 0], [0, 0]];
		for (let i = 0; i < n; i++) {
			cnt[a[i] - 0][b[i] - 0]++;
		}

		let ans = INF;
		if (cnt[1][1] == cnt[0][0] + 1) {
			ans = cnt[1][1] + cnt[0][0];
		}

		if (cnt[1][0] == cnt[0][1]) {
			ans = Math.min(ans, cnt[1][0] + cnt[0][1]);
		}

		console.log(ans == INF ? -1 : ans);
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 1e6;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rl();
		const b = rl();

		const cnt = [[0, 0], [0, 0]];
		for (let i = 0; i < n; i++) {
			cnt[a[i]-0][b[i]-0]++;
		}

		let ans = INF;
		if (cnt[1][1] == cnt[0][0] + 1 && (cnt[1][1] + cnt[0][0]) % 2 == 1) {
			ans = cnt[1][1] + cnt[0][0];
		}

		if (cnt[1][0] == cnt[0][1] && (cnt[1][0] + cnt[0][1]) % 2 == 0) {
			ans = Math.min(ans, cnt[1][0] + cnt[0][1]);
		}

		if (ans == INF) ans = -1;

		console.log(ans);
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 1e6;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rl();
		const b = rl();

		const cnt = [[0, 0], [0, 0]];
		for (let i = 0; i < n; i++) {
			cnt[a[i]-0][b[i]-0]++;
		}

		let ans = INF;
		if (cnt[1][1] >= cnt[0][0] && (cnt[1][1] + cnt[0][0]) % 2 == 1) {
			ans = cnt[1][1] + cnt[0][0];
		}

		if (cnt[1][0] >= cnt[0][1] && (cnt[1][0] + cnt[0][1]) % 2 == 0) {
			ans = Math.min(ans, cnt[1][0] + cnt[0][1]);
		}

		if (ans == INF) ans = -1;

		console.log(ans);
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 1e6;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rl();
		const b = rl();

		let sameCnt = 0, oppositeCnt = 0;
		for (let i = 0; i < n; i++) {
			if (a[i] == b[i]) sameCnt++; else oppositeCnt++;
		}

		let ans = INF;
		ans = Math.min(ans, (sameCnt & 1) == 1 ? sameCnt : INF);
		ans = Math.min(ans, (oppositeCnt & 1) == 0 ? oppositeCnt : INF);

		let ok;
		for (let i = 0; i < n; i++) ok |= a[i] == '1';
		if (!ok) ans = INF;

		console.log(ans == INF ? -1 : ans);
	}
}