A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.There is an $$$n\times m$$$ grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.  There is at least one south magnet in every row and every column.  If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.  If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement. Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 1000$$$)  — the number of rows and the number of columns, respectively. The next $$$n$$$ lines describe the coloring. The $$$i$$$-th of these lines contains a string of length $$$m$$$, where the $$$j$$$-th character denotes the color of the cell in row $$$i$$$ and column $$$j$$$. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.

Output a single integer, the minimum possible number of north magnets required. If there is no placement of magnets that satisfies all conditions, print a single integer $$$-1$$$.

NoteIn the first test, here is an example placement of magnets:  In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule $$$3$$$ since we can move the north magnet down onto a white square. The second example violates rule $$$2$$$ since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule $$$1$$$ since there is no south magnet in the first column.  In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.  In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule $$$1$$$ since there is no south magnet in the first row. The second example violates rules $$$1$$$ and $$$3$$$ since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.  In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    // if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
    if (foundFirstBlack === -1) {
      if (found[i - 1]) {
        for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
          closeForS.add(cs)
        }
      }
      i++;
      continue;
    }
    else {found[i] = [foundFirstBlack]}

    // if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundLastBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (

      (Object.keys(found).length !== l1 && closeForS.size === l2) ||
      (Object.keys(found).length === l1 && closeForS.size !== l2)

  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var blankLines1 = 0, blankLines2 = 0;
var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) {
        if (rc) {
            blankLines1 ++;
        } else {
            blankLines2 ++;
        }
    }
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

if ((blankLines2 === 0 && blankLines1 > 0) || (blankLines2 > 0 && blankLines1 === 0)) output = -1;

print(output);

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    // if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
    if (foundFirstBlack === -1) {
      if (i === l1 - 1) {
        for (cs = 0; cs <= l2; cs++) {
          closeForS.add(cs)
        }
      }
      i++;
      continue;
    }
    else {found[i] = [foundFirstBlack]}

    // if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundFirstBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (

      (Object.keys(found).length !== l1 && closeForS.size === l2) ||
      (Object.keys(found).length === l1 && closeForS.size !== l2)

  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let NOTFOUNDBLACK = false;
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
      else {found[i] = [foundFirstBlack]}

    if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundFirstBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack > foundFirstBlack && foundFirstWhiteInBlack < foundLastBlack) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (
    (Object.keys(test).length !== l1) && FOUNDBLACK
  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let NOTFOUNDBLACK = false;
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
      else {found[i] = [foundFirstBlack]}

    if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundFirstBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (
    (Object.keys(test).length !== l1 || closeForS.size !== l2) && FOUNDBLACK
  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    // if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
    if (foundFirstBlack === -1) {
      for (cs = 0; cs <= l2; cs++) {
        closeForS.add(cs)
      }
      i++;
      continue;
    }
    else {found[i] = [foundFirstBlack]}

    // if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundLastBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (

      (Object.keys(found).length !== l1 && closeForS.size === l2) ||
      (Object.keys(found).length === l1 && closeForS.size !== l2)

  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    // if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
    if (foundFirstBlack === -1) {
      if (i === l1 - 1) {
        for (cs = 0; cs <= l2; cs++) {
          closeForS.add(cs)
        }
      }
      i++;
      continue;
    }
    else {found[i] = [foundFirstBlack]}

    // if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundLastBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (

      (Object.keys(found).length !== l1 && closeForS.size === l2) ||
      (Object.keys(found).length === l1 && closeForS.size !== l2)

  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    // if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
    if (foundFirstBlack === -1) {
      if (i === l1 - 1) {
        for (cs = 0; cs <= l2; cs++) {
          closeForS.add(cs)
        }
      }
      i++;
      continue;
    }
    else {found[i] = [foundFirstBlack]}

    // if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundFirstBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (
    (
      (Object.keys(found).length !== l1 && closeForS.size !== l2)
      // (Object.keys(found).length === l1 && closeForS.size !== l2)
    ) && FOUNDBLACK
  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});
let l1, l2;
let test = [];
rl.on('line', (line) => {
  if (l1 === undefined && l2 === undefined) {
    const [l11, l22] = line.split(' ');

    l1 = +l11;
    l2 = +l22;
  } else {
    test.push(line.split(''));
  }
}).on('close', () => {
  let FOUNDBLACK = false;
  // кол-во островков и серверных магнитов
  let N = 0;
  // i => строка, j = столбец
  let i = 0;
  const found = {}; // строки
  const closeForS = new Set();

  while (i < l1) {
    const foundFirstBlack = test[i].indexOf('#');

    // if (foundFirstBlack === -1) {i++; NOTFOUNDBLACK = true; continue;}
    if (foundFirstBlack === -1) {
      if (i === l1 - 1) {
        for (cs = 0; cs <= l2; cs++) {
          closeForS.add(cs)
        }
      }
      i++;
      continue;
    }
    else {found[i] = [foundFirstBlack]}

    // if (NOTFOUNDBLACK) {N = -1; break;}

    FOUNDBLACK = true;

    const foundLastBlack = test[i].lastIndexOf('#');
    found[i].push(foundLastBlack);

    if (closeForS.has(foundFirstBlack) || closeForS.has(foundFirstBlack)) {N = -1; break;}

    const foundFirstWhiteInBlack = test[i].indexOf('.', foundFirstBlack);
    if (foundFirstWhiteInBlack >= found[i][0] && foundFirstWhiteInBlack <= found[i][1]) {N = -1; break;}

    if (found[i - 1] !== undefined) {
      for (cs = found[i - 1][0]; cs <= found[i - 1][1]; cs++) {
        if (cs < found[i][0] || cs > found[i][1]) closeForS.add(cs)
      }
    }

    if (
      found[i - 1] === undefined ||
      (foundFirstBlack < found[i - 1][0] && foundLastBlack < found[i - 1][0]) ||
      (foundFirstBlack > found[i - 1][1] && foundLastBlack > found[i - 1][1])
    ) {
      N++;
    }

    if (i === l1 -1) {
      for (cs = foundFirstBlack; cs <= foundLastBlack; cs++) {
        closeForS.add(cs)
      }
    }

    i++;
  }

  if (
    (
      (Object.keys(found).length !== l1 && closeForS.size === l2) ||
      (Object.keys(found).length === l1 && closeForS.size !== l2)
    ) && FOUNDBLACK
  ) {
    N = -1;
  }

  process.stdout.write(N.toString());
});

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var blankLines1 = 0, blankLines2 = 0;
var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) {
        if (rc) {
            blankLines1 ++;
        } else {
            blankLines2 ++;
        }
    }
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

if ((blankLines1 === 0 && blankLines2 === 0) || (blankLines1 > 1 && blankLines2 > 1)) output = -1;

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        if (g === '#') t2 = 1;
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fill = function(y, x) {
    var fillStack = [];
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 || grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t === 0 && output === 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t === 0 && output !== 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output); //

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    for (var x = 0; x < size[1]; x ++) {
        grid2.push(0); // empty
    }
}

var recur = function(x, y) {
    if (grid[y][x] === '#' && grid2[y][x] === 0) {
        grid2[y][x] = 1;
        if (size[0] > x + 1) recur(x + 1, y);
        if (1 <= x) recur(x - 1, y);
        if (size[1] > y + 1) recur(x, y + 1);
        if (1 <= y) recur(x, y - 1);
        return true;
    }
    return false;
};

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    if ('#.# #..# #...# #....# #.....# #......# #.......#'.includes(grid[y])) {
        output = -1;
        break;
    }
    for (var x = 0; x < size[1]; x ++) {
        if (recur(x, y)) output ++;
    }
}

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);//

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 || grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t === 0 && output === 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t === 0 && output === 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var blankLines1 = 0, blankLines2 = 0;
var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) {
        if (rc) {
            blankLines1 ++;
        } else {
            blankLines2 ++;
        }
    }
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

if ((blankLines1 !== 0 || blankLines2 !== 0) || (blankLines1 > 1 && blankLines2 > 1)) output = -1;

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var blankLines1 = 0, blankLines2 = 0;
var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) {
        if (rc) {
            blankLines1 ++;
        } else {
            blankLines2 ++;
        }
    }
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

if ((blankLines1 !== 0 || blankLines2 !== 0) && (blankLines1 <= 1 && blankLines2 <= 1)) output = -1;

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    for (var x = 0; x < size[1]; x ++) {
        grid2.push(0); // empty
    }
}

var recur = function(x, y) {
    if (grid[y][x] === '#' && grid[y][x] === 0) {
        grid[y][x] = 1;
        if (size[0] > x + 1) recur(x + 1, y);
        if (1 <= x) recur(x - 1, y);
        if (size[1] > y + 1) recur(x, y + 1);
        if (1 <= y) recur(x, y - 1);
        return true;
    }
    return false;
};

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (recur(x, y)) output ++;
    }
}

// rule 3 violation test
/*for (var y = 0; y < size[0]; y ++) {
    var test = 0; //
    for (var x = 0; x < size[1]; x ++) {
        if (grid[y][x] === '#') {
            if (test === 0) {
                test = 1; // hit black tile
            } else {
                output = -1;
            }
        } else if (test === 1) {
            test = 2; // hit white tile
        }
    }
}*/

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var blankLines = 0;
var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) blankLines ++;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

if (blankLines === 1) output = -1;

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    for (var x = 0; x < size[1]; x ++) {
        grid2.push(0); // empty
    }
}

var recur = function(x, y) {
    if (grid[y][x] === '#' && grid[y][x] === 0) {
        grid[y][x] = 1;
        if (size[0] > x + 1) recur(x + 1, y);
        if (1 <= x) recur(x - 1, y);
        if (size[1] > y + 1) recur(x, y + 1);
        if (1 <= y) recur(x, y - 1);
        return true;
    }
    return false;
};

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (recur(x, y)) output ++;
    }
}

// rule 3 violation test
for (var y = 0; y < size[0]; y ++) {
    var test = 0; //
    for (var x = 0; x < size[1]; x ++) {
        if (grid[y][x] === '#') {
            if (test === 0) {
                test = 1; // hit black tile
            } else {
                output = -1;
            }
        } else if (test === 1) {
            test = 2; // hit white tile
        }
    }
}

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var recur = function(x, y) {
    if (grid[y][x] === '#' && grid2[y][x] === 0) {
        grid2[y][x] = 1;
        if (size[1] > x + 1) recur(x + 1, y);
        if (x - 1 >= 0) recur(x - 1, y);
        if (size[0] > y + 1) recur(x, y + 1);
        if (y - 1 >= 0) recur(x, y - 1);
        return true;
    }
    return false;
};

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (recur(x, y)) output ++;
    }
}

var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t === 0 || output === 0) output = -1;
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var fillStack = [];
var fill = function(y, x) {
    fillStack.push([y, x]);
    while(fillStack.length > 0) {
        var t = fillStack.pop();
        y = t[0];
        x = t[1];
        if (y < 0 || y >= size[0] || x < 0 || x >= size[1]) continue;
        if (grid2[y][x] === 1 || grid[y][x] === '.') continue;
        grid2[y][x] = 1;
        fillStack.push([y + 1, x]);
        fillStack.push([y - 1, x]);
        fillStack.push([y, x + 1]);
        fillStack.push([y, x - 1]);
    }
}

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (grid2[y][x] === 0 && grid[y][x] === '#') {
            output ++;
            fill(y, x);
        }
    }
}

var blankLines1 = 0, blankLines2 = 0;
var check = function(rc, n) {
    var t = 0;
    var t2 = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]) && output !== -1; i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') {
                t = 1;
                t2 = 1;
            }
            break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                }
            break;
        }
    }
    if (t2 === 0 && output !== 0) {
        if (rc) {
            blankLines1 ++;
        } else {
            blankLines2 ++;
        }
    }
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

if ((blankLines1 !== 0 || blankLines2 !== 0) || !(blankLines1 > 1 && blankLines2 > 1)) output = -1;

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var recur = function(x, y) {
    if (grid[y][x] === '#' && grid2[y][x] === 0) {
        grid2[y][x] = 1;
        if (size[1] > x + 1) recur(x + 1, y);
        if (x - 1 >= 0) recur(x - 1, y);
        if (size[0] > y + 1) recur(x, y + 1);
        if (y - 1 >= 0) recur(x, y - 1);
        return true;
    }
    return false;
};

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (recur(x, y)) output ++;
    }
}

var check = function(rc, n) {
    var t = 0;
    for (var i = 0; i < (rc ? size[1] : size[0]); i ++) {
        var g = rc ? grid[n][i] : grid[i][n];
        switch(t) {
            case 0: if (g === '#') t = 1; break;
            case 1: if (g === '.') t = 2; break;
            case 2:
                if (g === '#') {
                    output = -1;
                    break;
                }
            break;
        }
    }
};

for (var y = 0; y < size[0] && output !== -1; y ++)
    check(true, y);
for (var x = 0; x < size[1] && output !== -1; x ++)
    check(false, x);

print(output);

var size = readline().split(' ').map(x => parseInt(x));
var grid = [], grid2 = [];
for (var y = 0; y < size[0]; y ++) {
    grid.push(readline());
    grid2.push([]);
    for (var x = 0; x < size[1]; x ++)
        grid2[y].push(0);
}

var recur = function(x, y) {
    if (grid[y][x] === '#' && grid2[y][x] === 0) {
        grid2[y][x] = 1;
        if (size[0] > x + 1) recur(x + 1, y);
        if (1 <= x) recur(x - 1, y);
        if (size[1] > y + 1) recur(x, y + 1);
        if (1 <= y) recur(x, y - 1);
        return true;
    }
    return false;
};

var output = 0;
for (var y = 0; y < size[0]; y ++) {
    for (var x = 0; x < size[1]; x ++) {
        if (recur(x, y)) output ++;
    }
}

print(output);


You play your favourite game yet another time. You chose the character you didn't play before. It has $$$str$$$ points of strength and $$$int$$$ points of intelligence. Also, at start, the character has $$$exp$$$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $$$1$$$ or raise intelligence by $$$1$$$).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain descriptions of queries — one per line. This line contains three integers $$$str$$$, $$$int$$$ and $$$exp$$$ ($$$1 \le str, int \le 10^8$$$, $$$0 \le exp \le 10^8$$$) — the initial strength and intelligence of the character and the number of free points, respectively.

Print $$$T$$$ integers — one per query. For each query print the number of different character builds you can create.

NoteIn the first query there are only three appropriate character builds: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ and $$$(9, 3)$$$. All other builds are either too smart or don't use all free points.In the second query there is only one possible build: $$$(2, 1)$$$.In the third query there are two appropriate builds: $$$(7, 6)$$$, $$$(8, 5)$$$.In the fourth query all builds have too much brains.

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var T = rdN();

    while (T --> 0) {
        var input = rdArN();
        var str = input[0];
        var int = input[1];
        var exp = input[2];

        var s = str+int+exp;
        var maxStr = str + exp;
        var minStr = Math.max(str, (s >> 1) + 1);
        var res = 0;
        if (maxStr >= minStr) {
            res = maxStr - minStr + 1;
        }

        pr(res);
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

'use strict';
const io = (function() {
  process.stdin.resume(); process.stdin.setEncoding('utf-8');
  let inputString = '', currentLine = 0, curTok = 0, input = [];
  function _check() { if (currentLine >= input.length) throw 'EOF!'; }
  process.stdin.on('data', data => { inputString += data; });
  process.stdin.on('end', _ => {
      for (const i of inputString.split('\n')) { input.push(i.split(' ')); }
      main();
  });
  function nextLine() {
    _check();
    const ret = input[currentLine++].slice(curTok).join(' ');
    curTok = 0;
    return ret;
  }
  function next() {
    _check();
    while (curTok == input[currentLine].length) {
      currentLine++;
      curTok = 0;
      _check()
    }
    return input[currentLine][curTok++];
  }
  function nextInt() { return parseInt(next()); }
  return {
    nextLine: nextLine,
    next: next,
    nextInt: nextInt,
  };
})();

function poss(s, i, e, tar) {
  if (tar < s) return false;
  const need = tar - s;
  if (need > e) return false;
  s += need;
  i += e - need;
  return s > i;
}

function deal() {
  let s = io.nextInt();
  let i = io.nextInt();
  let e = io.nextInt();
  let ans = -1;
  if (s + e <= i) {
    ans = 0;
  } else {
    //lowest value that is possible
    let lo = 0;   //not possible
    let hi = s+e; //possible
    while (lo < hi - 1) {
      let guess = Math.floor((lo + hi) / 2);
      if (poss(s, i, e, guess)) {
        hi = guess;
      } else {
        lo = guess;
      }
    }
    ans = s+e - hi + 1;
  }
  console.log(ans);
}

function main() {
  let T = io.nextInt();
  while (T > 0) {
    deal();
    T--;
  }
}

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 noOfQueries = parseInt(arr.shift())
  for(let i = 0; i < noOfQueries; i++){
    // if exp === 0
    // else
    const queries = arr[i].split(' ');
    const str = parseInt(queries[0])
    const intellect = parseInt(queries[1])
    let exp = parseInt(queries[2])
    if(str == intellect){
      if(exp == 0){
        console.log(0)
      }
      else console.log(Math.ceil(exp / 2))
    }
    else if(str < intellect){
      if(intellect - str >= exp) console.log(0)
      else{
        exp = exp - intellect + str
        console.log(Math.ceil(exp / 2))
      }
    }
    else{
      if(str - intellect > exp) console.log(exp + 1)
      else if (str - intellect == exp) console.log(exp)
      else{
        const diff = str - intellect
        console.log(Math.ceil((exp - diff) / 2) + diff)
      }
    }
  }
})

const MEMORY = [];
let MEMORY_INDEX = 0;
function print() {
   console.log.apply(null, arguments);
}
function readline() {
   return MEMORY[MEMORY_INDEX++];
}

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

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

RL.on('close', solve);

function solve() {
   const T = Number.parseInt(readline(), 10);
   for (let i = 0; i < T; ++i) {
      let [str, int, exp] = readline().split(' ').map(n => Number.parseInt(n, 10));
      if (str + exp <= int) {
         print(0);
         continue;
      }
      let maxStr = str + exp;
      let minStr = Math.max((str + exp + int + 2) >> 1, str);
      print(maxStr - minStr + 1);
   }
}

let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  for (let i = 1; i < lines.length; i++) {
    const parts = lines[i].split(' ');
    if (parts.length === 3) {
      console.log(creating(parseInt(parts[0], 10), parseInt(parts[1], 10), parseInt(parts[2], 10)));
    }
  }
});

function creating(str, int, exp) {
  if (str + exp <= int) return 0;
  const diff = str + exp - int;
  return diff % 2 === 0 ? Math.min(Math.floor(diff / 2), exp + 1) : Math.min(1 + (Math.floor(diff / 2)), exp + 1);
}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var T = rdN();

    while (T --> 0) {
        var input = rdArN();
        var str = input[0];
        var int = input[1];
        var exp = input[2];

        var s = str+int+exp;
        var minStr = (s >> 1) + 1;
        var maxInt = s - minStr;

        var freeInt = maxInt - int + 1;

        pr(freeInt > 0 ? freeInt : 0);
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

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 noOfQueries = parseInt(arr.shift())
  for(let i =0; i < noOfQueries; i++){
    // if exp === 0
    // else
    const queries = arr[i].split(' ');
    const str = parseInt(queries[0])
    const int = parseInt(queries[1])
    let exp = parseInt(queries[2])
    if(str == int){
      if(exp == 0){
        console.log(0)
      }
      else console.log(Math.ceil(exp / 2))
    }
    else if(str < int){
      if(int - str >= exp) console.log(0)
      else{
        exp = exp - int + str
        console.log(Math.ceil(exp / 2))
      }
    }
    else{
      exp = exp + str - int
      console.log(Math.ceil(exp / 2))
    }
  }
})

const MEMORY = [];
let MEMORY_INDEX = 0;
function print() {
   console.log.apply(null, arguments);
}
function readline() {
   return MEMORY[MEMORY_INDEX++];
}

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

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

RL.on('close', solve);

function solve() {
   const T = Number.parseInt(readline(), 10);
   for (let i = 0; i < T; ++i) {
      let [str, int, exp] = readline().split(' ').map(n => Number.parseInt(n, 10));
      let maxDiff = str + exp - int + 1;
      if (maxDiff <= 1) {
         print(0);
      } else {
         print((maxDiff >> 1));
      }
   }
}

const MEMORY = [];
let MEMORY_INDEX = 0;
function print() {
   console.log.apply(null, arguments);
}
function readline() {
   return MEMORY[MEMORY_INDEX++];
}

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

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

RL.on('close', solve);

function solve() {
   const T = Number.parseInt(readline(), 10);
   for (let i = 0; i < T; ++i) {
      let [str, int, exp] = readline().split(' ').map(n => Number.parseInt(n, 10));
      if (str + exp <= int) {
         print(0);
         continue;
      }
      let maxStr = str + exp;
      let minStr = (str + exp + int + 2) >> 1;
      print(maxStr - minStr + 1);
   }
}


There were $$$n$$$ types of swords in the theater basement which had been used during the plays. Moreover there were exactly $$$x$$$ swords of each type. $$$y$$$ people have broken into the theater basement and each of them has taken exactly $$$z$$$ swords of some single type. Note that different people might have taken different types of swords. Note that the values $$$x, y$$$ and $$$z$$$ are unknown for you.The next morning the director of the theater discovers the loss. He counts all swords — exactly $$$a_i$$$ swords of the $$$i$$$-th type are left untouched.The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.For example, if $$$n=3$$$, $$$a = [3, 12, 6]$$$ then one of the possible situations is $$$x=12$$$, $$$y=5$$$ and $$$z=3$$$. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values $$$x, y$$$ and $$$z$$$ beforehand but know values of $$$n$$$ and $$$a$$$.Thus he seeks for your help. Determine the minimum number of people $$$y$$$, which could have broken into the theater basement, and the number of swords $$$z$$$ each of them has taken.

The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of types of swords. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^{9})$$$, where $$$a_i$$$ equals to the number of swords of the $$$i$$$-th type, which have remained in the basement after the theft. It is guaranteed that there exists at least one such pair of indices $$$(j, k)$$$ that $$$a_j \neq a_k$$$.

Print two integers $$$y$$$ and $$$z$$$ — the minimum number of people which could have broken into the basement and the number of swords each of them has taken.

NoteIn the first example the minimum value of $$$y$$$ equals to $$$5$$$, i.e. the minimum number of people who could have broken into the basement, is $$$5$$$. Each of them has taken $$$3$$$ swords: three of them have taken $$$3$$$ swords of the first type, and two others have taken $$$3$$$ swords of the third type.In the second example the minimum value of $$$y$$$ is $$$1$$$, i.e. the minimum number of people who could have broken into the basement, equals to $$$1$$$. He has taken $$$7$$$ swords of the first type.

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

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

// numberTheory.ts

// function gcd(a: number, b: number) {
//   if (b == 0) {
//     return a
//   }
//
//   return gcd(b, a % b)
// }
//
// export { gcd }

// import './array'
//
// import io from './io'
// import { gcd } from './numberTheory'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let m = a.max()
//
//   let r = -1
//
//   for (let x of a) {
//     if (x == m) {
//       continue
//     }
//     if (r == -1) {
//       r = m - x
//       continue
//     }
//     r = gcd(m - x, r)
//   }
//
//   let s = 0
//
//   for (let x of a) {
//     s += (m - x) / r
//   }
//
//   io.puts(s + " " + r)
// }
//
// // io.runEachTest(main)
// io.runMain(main)

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

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

// import './array'
//
// import io from './io'
// import { gcd } from './numberTheory'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let m = a.max()
//
//   let r = -1
//
//   for (let x of a) {
//     if (x == m) {
//       continue
//     }
//     if (r == -1) {
//       r = m - x
//       continue
//     }
//     r = gcd(m - x, r)
//   }
//
//   let s = 0
//
//   for (let x of a) {
//     s += (m - x) / r
//   }
//
//   io.puts(s + " " + r)
// }
//
// // io.runEachTest(main)
// io.runMain(main)

'use strict'

const n = parseInt(readline());
let m = readline().split(' ').map(Number);

const gcd = (a,b) => {
    if (a < b) { const c = a; a = b; b = c; }
    while(b) { const c = a % b; a = b; b = c; }
    return a;
};

m = m.sort((a, b) => b - a);
const d = m.slice(1).map(i => m[0] - i).filter(Boolean);
const z = d.slice(1).reduce((r, i) => gcd(r, i), d[0]);
const y = d.reduce((r, i) => r + i, 0) / z;
write(y + ' ' + z);

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

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

// import './array'
//
// import io from './io'
// import { gcd } from './numberTheory'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let m = a.max()
//
//   let r = m
//
//   for (let x of a) {
//     r = gcd(x, r)
//   }
//
//   let s = 0
//
//   for (let x of a) {
//     s += (m - x) / r
//   }
//
//   io.puts(s + " " + r)
// }
//
// // io.runEachTest(main)
// io.runMain(main)

'use strict'

const n = parseInt(readline());
let m = readline().split(' ').map(Number);

const gcd = (a,b) => {
    if (a < b) { const c = a; a = b; b = a; }
    while(b) { const c = a % b; a = b; b = c; }
    return a;
};

m = m.sort((a, b) => b - a);
const d = m.slice(1).map(i => m[0] - i).filter(Boolean);
const z = gcd(d[0], d[d.length - 1]);
const y = d.reduce((r, i) => r + i, 0) / z;
write(y + ' ' + z);

'use strict'

const n = parseInt(readline());
let m = readline().split(' ').map(Number);

const gcd = (a,b) => {
    if (a < b) { const c = a; a = b; b = c; }
    while(b) { const c = a % b; a = b; b = c; }
    return a;
};

m = m.sort((a, b) => b - a);
const d = m.slice(1).map(i => m[0] - i).filter(Boolean);
const z = gcd(d[0], d[d.length - 1]);
const y = d.reduce((r, i) => r + i, 0) / z;
write(y + ' ' + z);


Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string $$$s$$$ of lowercase Latin letters. She considers a string $$$t$$$ as hidden in string $$$s$$$ if $$$t$$$ exists as a subsequence of $$$s$$$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $$$1$$$, $$$3$$$, and $$$5$$$, which form an arithmetic progression with a common difference of $$$2$$$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $$$S$$$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden $$$3$$$ times, b is hidden $$$2$$$ times, ab is hidden $$$6$$$ times, aa is hidden $$$3$$$ times, bb is hidden $$$1$$$ time, aab is hidden $$$2$$$ times, aaa is hidden $$$1$$$ time, abb is hidden $$$1$$$ time, aaab is hidden $$$1$$$ time, aabb is hidden $$$1$$$ time, and aaabb is hidden $$$1$$$ time. The number of occurrences of the secret message is $$$6$$$.

The first line contains a string $$$s$$$ of lowercase Latin letters ($$$1 \le |s| \le 10^5$$$) — the text that Bessie intercepted.

Output a single integer  — the number of occurrences of the secret message.

NoteIn the first example, these are all the hidden strings and their indice sets:   a occurs at $$$(1)$$$, $$$(2)$$$, $$$(3)$$$  b occurs at $$$(4)$$$, $$$(5)$$$  ab occurs at $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,4)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$  aa occurs at $$$(1,2)$$$, $$$(1,3)$$$, $$$(2,3)$$$  bb occurs at $$$(4,5)$$$  aab occurs at $$$(1,3,5)$$$, $$$(2,3,4)$$$  aaa occurs at $$$(1,2,3)$$$  abb occurs at $$$(3,4,5)$$$  aaab occurs at $$$(1,2,3,4)$$$  aabb occurs at $$$(2,3,4,5)$$$  aaabb occurs at $$$(1,2,3,4,5)$$$  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

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

    C();
});

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

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

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

    return a;
}

function C(){
    let s = readline().split('');
    let c = 'abcdefghijklmnopqrstuvwxyz'.split('');
    let map = new Array(26);
    let cMap = {};
    map.fill(0);
    for(let i = 0; i < s.length; i++){
        let index = s[i].charCodeAt(0)-97;
        for(let j = 0; j < 26; j++){
            if(map[j] !== 0){
                if(cMap[`${c[j]}${c[index]}`] !== undefined){
                    cMap[`${c[j]}${c[index]}`] += map[j];
                }else{
                    cMap[`${c[j]}${c[index]}`] = map[j];
                }
            }
        }
        map[index] += 1;
    }

    let max = 0;
    for(let i = 0; i < 26; i++)
        max = Math.max(max, map[i]);
    for(let m in cMap){
        max = Math.max(max,cMap[m]);
    }
    console.log(max);
}


Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.

The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer mi (1 ≤ mi ≤ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers ai, 1, ai, 2, ..., ai, mi (1 ≤ ai, k ≤ 100) — the numbers on the i-th player's card. The numbers in the lines are separated by single spaces. It is guaranteed that all the numbers on each card are distinct.

Print n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise.

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var playerNum = integers[0];

	var cards = [];
	for (var i = 0; i < playerNum; i += 1) {
		cards.push(tokenizeIntegers(readline()).slice(1));
	}

	for (var i = 0; i < playerNum; i += 1) {
		var playerCard = cards[i];
		var canWin = true;
		for (var j = 0; j < playerNum; j += 1) {
			if (j == i) {
				continue;
			}
			var testCard = cards[j];
			var covers = true;
			for (var k = 0; k < testCard.length; k += 1) {
				var foundIt = false;
				for (var ii = 0; ii < playerCard.length; ii += 1) {
					if (playerCard[ii] == testCard[k]) {
						foundIt = true;
						break;
					}
				}
				if (foundIt == false) {
					covers = false;
					break;
				}
			}
			if (covers) {
				canWin = false;
				break;
			}
		}
		print(canWin ? 'YES' : 'NO');
	}

}

main();


Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.

The first line of the input file contains integers n and x0 (1 ≤ n ≤ 100; 0 ≤ x0 ≤ 1000). The following n lines contain pairs of integers ai, bi (0 ≤ ai, bi ≤ 1000; ai ≠ bi).

Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var segmentNum = integers[0], startPos = integers[1];

	var cover = new Array(1001);
	for (var i = 0; i <= 1000; i += 1) {
		cover[i] = 0;
	}

	for (var i = 0; i < segmentNum; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = Math.min(integers[0], integers[1]);
		var b = Math.max(integers[0], integers[1]);
		for (var j = a; j <= b; j += 1) {
			cover[j] += 1;
		}
	}

	var best = -1;

	for (var i = startPos; i >= 0; i -= 1) {
		if (cover[i] == segmentNum) {
			best = startPos-i;
			break;
		}
	}

	for (var i = startPos; i <= 1000; i += 1) {
		if (cover[i] == segmentNum && (best === -1 || i-startPos < best)) {
			best = i-startPos;
			break;
		}
	}

	print(best);
}

main();

'use strict'

let lll = readline().split(' ')
const N = lll[0]
const X = lll[1]

var spos = []

while (lll = readline()) spos.push(lll.split(' ').map(v => +v))

spos = spos.map(s => s[0] < s[1] ? s : [s[1], s[0]])

let p = spos.reduce((p, s) => [Math.max(p[0], s[0]), Math.min(p[1], s[1])])

if (p[0] > p[1]) {
  print(-1)
} else {
  if (p[0] <= X && X <= p[1]) {
    print(0)
  } else if (p[0] > X){
    print(p[0] - X)
  } else {
    print(X - p[1])
  }
}

var nxo = readline().split(' ').map(Number);
var n = nxo[0];
var x0 = nxo[1];
var x1 = 0;
var x2 = 1100;
for (var i=0; i<n; i++){
	var l = readline().split(' ').map(Number).sort( (a,b) => a-b );
	if (l[0] > x1) x1 = l[0];
	if (l[1] < x2) x2 = l[1];
}
if (x2-x1<0) print(-1);
else if (x0-x1>=0 && x2-x0>=0) print(0);
else {
	print ( Math.min( Math.abs(x0-x1), Math.abs(x0-x2) ) );
}

'use strict'

let lll = readline().split(' ')
const N = lll[0]
const X = lll[1]

var spos = []

while (lll = readline()) spos.push(lll.split(' ').map(v => +v))

spos = spos.map(s => s[0] < s[1] ? s : [s[1], s[0]])

let p = spos.reduce((p, s) => [Math.max(p[0], s[0]), Math.min(p[1], s[1])])

if (p[0] > p[1]) {
  print(-1)
} else {
  if (p[0] < X && X < p[1]) {
    print(0)
  } else if (p[0] > X){
    print(p[0] - X)
  } else {
    print(X - p[1])
  }
}


This is the hard version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.Tokitsukaze has a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones, $$$n$$$ is even.Now Tokitsukaze divides $$$s$$$ into the minimum number of contiguous subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $$$s$$$ is considered good if the lengths of all subsegments are even.For example, if $$$s$$$ is "11001111", it will be divided into "11", "00" and "1111". Their lengths are $$$2$$$, $$$2$$$, $$$4$$$ respectively, which are all even numbers, so "11001111" is good. Another example, if $$$s$$$ is "1110011000", it will be divided into "111", "00", "11" and "000", and their lengths are $$$3$$$, $$$2$$$, $$$2$$$, $$$3$$$. Obviously, "1110011000" is not good.Tokitsukaze wants to make $$$s$$$ good by changing the values of some positions in $$$s$$$. Specifically, she can perform the operation any number of times: change the value of $$$s_i$$$ to '0' or '1' ($$$1 \leq i \leq n$$$). Can you tell her the minimum number of operations to make $$$s$$$ good? Meanwhile, she also wants to know the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the length of $$$s$$$, it is guaranteed that $$$n$$$ is even. The second line contains a binary string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single line with two integers — the minimum number of operations to make $$$s$$$ good, and the minimum number of subsegments that $$$s$$$ can be divided into among all solutions with the minimum number of operations.

NoteIn the first test case, one of the ways to make $$$s$$$ good is the following.Change $$$s_3$$$, $$$s_6$$$ and $$$s_7$$$ to '0', after that $$$s$$$ becomes "1100000000", it can be divided into "11" and "00000000", which lengths are $$$2$$$ and $$$8$$$ respectively, the number of subsegments of it is $$$2$$$. There are other ways to operate $$$3$$$ times to make $$$s$$$ good, such as "1111110000", "1100001100", "1111001100", the number of subsegments of them are $$$2$$$, $$$4$$$, $$$4$$$ respectively. It's easy to find that the minimum number of subsegments among all solutions with the minimum number of operations is $$$2$$$.In the second, third and fourth test cases, $$$s$$$ is good initially, so no operation is required.

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 str = lines[l++]
        output[i] = solve(n, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str) {
    let ans = 0
    let count = 0
    let p
    for (let i = 0; i < n; i += 2) {
        const a = str[i]
        const b = str[i + 1]
        if (a === b) {
            if (a === p) {
                //
            } else {
                count++
                p = a
            }
        } else {
            //
            ans++
        }
    }
    return ans + ' ' + Math.max(count, 1)
}

'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;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let s = readline();
  LT({n, s});
  // PROCESSING:
  let D = [new Array(n).fill(0), new Array(n).fill(0)];
  let C = [new Array(n).fill(0), new Array(n).fill(0)];
  let cost = (want, pos)=>+s[pos]==want ? 0 : 1;
  // D[ends with][pos]
  for (let i=1; i<n; i+=2){
    // ends with 1
    let op1 = (D[1][i-2]||0)+cost(1, i-1)+cost(1, i);
    let op0 = (D[0][i-2]||0)+cost(1, i-1)+cost(1, i);
    if (op1<=op0){
      D[1][i] = op1;
      C[1][i] = C[1][i-2]||1;
    } else {
      D[1][i] = op0;
      C[1][i] = (C[0][i-2]||1)+1;
    }
    // ends with 0
    op1 = (D[1][i-2]||0)+cost(0, i-1)+cost(0, i);
    op0 = (D[0][i-2]||0)+cost(0, i-1)+cost(0, i);
    D[0][i] = Math.min(op1, op0);
    if (op1<op0){
      D[0][i] = op1;
      C[0][i] = (C[1][i-2]||1)+1;
    } else {
      D[0][i] = op0;
      C[0][i] = C[0][i-2]||1;
    }
  }
  if (D[1][n-1]==D[0][n-1]){
    if (C[1][n-1]<C[0][n-1]){
      return `${D[1][n-1]} ${C[1][n-1]}`;
    } else {
      return `${D[0][n-1]} ${C[0][n-1]}`;
    }
  }
  if (D[1][n-1]<D[0][n-1]){
    return `${D[1][n-1]} ${C[1][n-1]}`;
  } else {
    return `${D[0][n-1]} ${C[0][n-1]}`;
  }
};

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, s)=>{
    let result = 0;

    let last = -1;
    let segs = 0;

    for (let i = 0; i < n; i += 2) {
        if (s[i] !== s[i + 1]) result++;
        else {
            if (s[i] !== last) {
                segs++;
                last = s[i];
            }
        }
    }
    if (!segs) segs = 1;

    return `${result} ${segs}`;

    // let segs = [];
    // let length = 1;
    // let cur = s[0];

    // for (let i = 1; i < n; i++) {
    //     if (s[i] !== cur) {
    //         segs.push([length, cur]);
    //         length = 1;
    //         cur = s[i];
    //     } else {
    //         length++;
    //     }
    // }
    // segs.push([length, cur]);
    // console.log(`DEBUG segs`, segs);

    // let m = segs.length;
    // for (let i = 0; i < m; i++) {
    //     let [l, bit] = segs[i];
    //     console.log(`DEBUG i ${i} l ${l} bit`, bit);
    //     if (l % 2 === 0) continue;
    //     let sumSame = 0; let sumDif = 0;
    //     for (let j = i + 1; j < m; j++) {
    //         let [lj, bitj] = segs[j];
    //         console.log(`DEBUG j ${j} lj ${lj} bitj`, bitj);
    //         if (lj % 2 === 0) {
    //             if (bitj === bit) sumSame += lj;
    //             else sumDif += lj;
    //         } else {
    //             if (bitj === bit) {
    //                 result += Math.min(sumDif, sumSame + 2);
    //             } else {
    //                 result += Math.min(sumDif, sumSame) + 1;
    //             }
    //             console.log(`DEBUG result`, result);
    //             i = j;
    //             break;
    //         }
    //     }
    // }

    // return result;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let s = readline();
        // let a = ra();
        out.push(calc(n, s));
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
var _loop_1 = function (i) {
    var n = +readline();
    var a = readline().split('').map(function (v) { return +v; });
    function f(cur) {
        var count = 0;
        var changes = 1;
        for (var i_1 = 0; i_1 < n / 2; i_1++) {
            if (a[i_1 * 2] !== a[i_1 * 2 + 1]) {
                count += 1;
            }
            else {
                if (cur !== a[i_1 * 2]) {
                    cur = a[i_1 * 2];
                    changes += 1;
                }
            }
        }
        return [count, changes];
    }
    var ans = [f(0), f(1)];
    print(ans[0][1] < ans[1][1] ? "".concat(ans[0][0], " ").concat(ans[0][1]) : "".concat(ans[1][0], " ").concat(ans[1][1]));
};
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var i = _a[_i];
    _loop_1(i);
}

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 str = lines[l++]
        output[i] = solve(n, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str) {
    let s = -1, p
    const ps = []
    for (let i = 0; i < n; i++) {
        const x = str[i]
        if (x !== p) {
            if (s >= 0) {
                ps.push(str.slice(s, i))
            }
            s = i
            p = x
        }
    }
    if (s < n) {
        ps.push(str.slice(s, n))
    }
// console.log(ps)
    let i = 0
    let ans = 0
    let count = 0
    let add = 0
    let zero = 0
    let prev
    while (i < ps.length) {
        const x = ps[i].length + add
        if (x & 1) {
            ans++
            if (x === 1) {
                add = 1
                zero = 1
            } else if (i + 1 < ps.length && ps[i + 1].length <= 2) {
                add = -1
            } else {
                add = 1
            }
        } else {
            add = 0
            if (x === 0) {
                zero = 1
            } else {
                zero = 0
            }
        }
        //
        // console.log(zero, count)
        if (zero) {
            zero = 0
        } else if (ps[i][0] !== prev) {
            count++
            prev = ps[i][0]
        }
        //
        i++
    }
    return ans + ' ' + count
}

'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;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let s = readline();
  LT({n, s});
  // PROCESSING:
  let D = [new Array(n).fill(0), new Array(n).fill(0)];
  let C = [new Array(n).fill(0), new Array(n).fill(0)];
  let cost = (want, pos)=>+s[pos]==want ? 0 : 1;
  // D[ends with][pos]
  for (let i=1; i<n; i+=2){
    // ends with 1
    let op1 = Math.max((D[1][i-2]||0)+cost(1, i-1)+cost(1, i));
    let op0 = Math.max((D[0][i-2]||0)+cost(1, i-1)+cost(1, i));
    if (op1<=op0){
      D[1][i] = op1;
      C[1][i] = C[1][i-2]||1;
    } else {
      D[1][i] = op0;
      C[1][i] = (C[0][i-2]||1)+1;
    }
    // ends with 0
    op1 = Math.max((D[1][i-2]||0)+cost(0, i-1)+cost(0, i));
    op0 = Math.max((D[0][i-2]||0)+cost(0, i-1)+cost(0, i));
    D[0][i] = Math.min(op1, op0);
    if (op1<op0){
      D[0][i] = op1;
      C[0][i] = (C[1][i-2]||1)+1;
    } else {
      D[0][i] = op0;
      C[0][i] = C[0][i-2]||1;
    }
  }
  if (D[1][n-1]<D[0][n-1]){
    return `${D[1][n-1]} ${C[1][n-1]}`;
  } else {
    return `${D[0][n-1]} ${C[0][n-1]}`;
  }
};