const gets = (() => {
  const lines = [];

  require("readline")
    .createInterface({
      input: process.stdin,
      output: process.stdout
    })
    .on("line", line => {
      if (lines.length > 0 && typeof lines[0] === "function") {
        lines.shift()(line);
      } else {
        lines.push(line);
      }
    });

  return async () => {
    if (lines.length > 0 && typeof lines[0] === "string") {
      return lines.shift();
    }
    return new Promise(resolve => lines.push(resolve));
  };
})();

const get_nums = async () => (await gets()).split(" ").map(x => Number(x));

function build(a) {
  const n = a.length;
  const s = new Array(n + 1);
  s.fill(0);
  let c = 0;
  for (let i = 0; i < n; i++) {
    if (a[i] === 0) {
      c = 0;
    } else {
      c++;
      s[c]++;
    }
  }
  for (let i = n - 1; i >= 0; i--) {
    s[i] += s[i + 1];
  }
  return s;
}

async function main() {
  const [n, m, k] = await get_nums();
  const a = await get_nums();
  const b = await get_nums();
  const sa = build(a);
  const sb = build(b);
  const calc = (w, h) => w <= n && h <= m ? sa[w] * sb[h] : 0;

  let ans = 0;
  for (let i = 1; i * i <= k; i++) {
    if (k % i !== 0) {
      continue;
    }
    ans += calc(i, k / i);
    if (i !== k / i) {
      ans += calc(k / i, i);
    }
  }
  console.log(ans);
}

main();

function solv() {
    var ip = readline().split(' ').map(x => parseInt(x))

    var x = ip[0]
    var y = ip[1]
    var pp = ip[2]

    var s = readline().split(' ').map(x => parseInt(x))
    var z = readline().split(' ').map(x => parseInt(x))

    var precZ = {}
    var ct = 0
    for (n = 0; n < y; n++) {
        if (z[n]) ct++;
        else {
            if (precZ[ct] == null) precZ[ct] = 1;
            else precZ[ct] += 1;
            ct = 0;
        }
    }
    if (ct) {
        if (precZ[ct] == null) precZ[ct] = 1;
        else precZ[ct] += 1;
    }

    ct = 0
    var segsZ = JSON.parse(JSON.stringify(precZ))
    var propz = []
    for (var n in precZ) {
        propz.push([n * 1, precZ[n]])
    }
    propz.sort((a, b) => {
        return b[0] - a[0]
    })

    for (var n = 0; n < propz.length; n++) {
        for (var k = propz[n][0] - 1; k >= 1; k--) {
            segsZ[k] = segsZ[k] == null ? (propz[n][0] - k + 1) * propz[n][1] : segsZ[k] + (propz[n][0] - k + 1) * propz[n][1];
        }
    }

    var precS = {}
    ct = 0
    for (var n = 0; n < x; n++) {
        if (s[n]) ct++;
        else {
            if (precS[ct] == null) precS[ct] = 1;
            else precS[ct] += 1;
            ct = 0;
        }
    }
    if (ct) {
        if (precS[ct] == null) precS[ct] = 1;
        else precS[ct] += 1;
    }

    ct = 0
    var segsS = JSON.parse(JSON.stringify(precS))
    var props = []
    for (var n in precS) {
        props.push([n * 1, precS[n]])
    }
    props.sort((a, b) => {
        return b[0] - a[0]
    })

    for (var n = 0; n < props.length; n++) {
        for (var k = props[n][0] - 1; k >= 1; k--) {
            segsS[k] = segsS[k] == null ? (props[n][0] - k + 1) * props[n][1] : segsS[k] + (props[n][0] - k + 1) * props[n][1];
        }
    }

    var res = 0;

    for (var n = 1; n * n <= pp; n++) {
        if (pp % n == 0 && n * n != pp) {
            res += (segsS[n] == null ? 0 : segsS[n]) * (segsZ[pp / n] == null ? 0 : segsZ[pp / n])
            res += (segsZ[n] == null ? 0 : segsZ[n]) * (segsS[pp / n] == null ? 0 : segsS[pp / n])
        }
        else res += (segsS[n] == null ? 0 : segsS[n]) * (segsZ[pp / n] == null ? 0 : segsZ[pp / n])
    }

    print(res)
}

var tc = 1;
//tc = parseInt(readline());
while (tc--) solv()

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0) {
      if (acc > 0) {
        aNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }

  if (acc>0) {
    aNums.push(acc)
  }

  // console.log(a)
  // console.log(aNums)

  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0) {
      if (acc > 0) {
        bNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  let sum = 0
  //
  // const aRed = aNums.sort((a, b) => a - b).reduce((r, x) => {
  //   const last = r[r.length-1]
  //   if (x === last[0]) {
  //     last[1]++
  //   } else {
  //     r.push([x, 1])
  //   }
  //   return r
  // }, [[1, 0]])
  //
  // const bRed = bNums.sort((a, b) => a - b).reduce((r, x) => {
  //   const last = r[r.length-1]
  //   if (x === last[0]) {
  //     last[1]++
  //   } else {
  //     r.push([x, 1])
  //   }
  //   return r
  // }, [[1, 0]])

  const f = factors(k).sort((a, b) => a-b)

  for (const t1 of f) {
    const t2 = k / t1
    const aWidth = aNums.reduce( (r, x) => r + (x >= t1 ? (x - t1 + 1 ) : 0), 0)
    const bWidth = bNums.reduce( (r, y) => r + (y >= t2 ? (y - t2 + 1 ) : 0), 0)
    sum += aWidth * bWidth
  }

  console.log(sum)
}

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

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0) {
      if (acc > 0) {
        aNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }

  if (acc>0) {
    aNums.push(acc)
  }

  // console.log(a)
  // console.log(aNums)

  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0) {
      if (acc > 0) {
        bNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  let sum = 0

  const aRed = aNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const bRed = bNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const f = factors(k)

  for (const [x, xCount] of aRed) {
    for (const [y, yCount] of bRed) {
      const s = x*y
      // console.log([x, y])
      if (s >= k) {

        for (const t1 of f) {

          const t2 = k / t1
          // console.log(t1, t2)
          if (t1 <= x && t2 <= y) {
            // console.log(t1, t2)
            // console.log(x-t1+1, y-t2+1)
            sum += (x-t1+1) * (y-t2+1) * xCount * yCount
          }
        }
      }
    }
  }

  // console.log(hashMap)

  // for (const key in hashMap) {
  //   const [x, y] = key.split('_').map(x => +x)
  //   // console.log(k, x, y)
  //   let localSum = 0

  //   // console.log(localSum)
  //   // console.log(hashMap[key])
  //   sum = localSum * hashMap[key]
  // }

  console.log(sum)
}

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

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0) {
      if (acc > 0) {
        aNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }

  if (acc>0) {
    aNums.push(acc)
  }

  // console.log(a)
  // console.log(aNums)

  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0) {
      if (acc > 0) {
        bNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  let sum = 0

  const aRed = aNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const bRed = bNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const f = factors(k).sort((a, b) => a-b)

  for (const t1 of f) {
    const t2 = k / t1
    const aWidth = aRed.reduce( (r, [x, c]) => r + (x >= t1 ? (x - t1 + 1 ) * c : 0), 0)
    const bWidth = bRed.reduce( (r, [y, c]) => r + (y >= t2 ? (y - t2 + 1 ) * c : 0), 0)
    sum += aWidth * bWidth
  }

  console.log(sum)
}

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

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

  let inputString = '';
  let currentLine = 0;

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

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

    main();
  });

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

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

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

const getFactors = (n) => {
  const result = new Set();
  for (let i = 1; i <= parseInt(n ** (1/2)); i++) {
    if (n % i === 0) {
      result.add(i);
      result.add(n / i);
    }
  }
  // print(result)
  return Array.from(result);
};

const getChunks = (arr) => {
  const result = {};
  let left = 0;
  arr.concat(0).forEach((x, i) => {
    if (x === 0) {
      result[i - left] = (result[i - left] || 0) + 1;
      left = i + 1;
    }
  })
  return result;
};

const main = () => {
  const [n, m, k] = readline().split(' ').map(x => parseInt(x));
  const a = readline().split(' ').map(x => parseInt(x));
  const b = readline().split(' ').map(x => parseInt(x));

  const factors = getFactors(k);
  const solve = (n, m) => {
    let cnt = 0;
    for (let i = 0; i < factors.length; i++) {
      const a = factors[i];
      const b = k / factors[i];
      if (n >= a && m >= b) cnt += (n - a + 1) * (m - b + 1);
    }
    return cnt
  };

  const note = new Map();

  let cnt = 0;
  const a_chunks = getChunks(a);
  const b_chunks = getChunks(b);
  for (const x in a_chunks) {
    for (const y in b_chunks) {
      const key = [x, y].join(',');
      const cached = note.get(key);
      if (cached !== undefined) {
        cnt += cached * a_chunks[x] * b_chunks[y];
      } else {
        const calc = solve(x, y);
        cnt += calc * a_chunks[x] * b_chunks[y];
        note.set(key, calc);
      }
    }
  }
  // print(note)
  // print(factors);
  // print(a_chunks, b_chunks);
  print(cnt);
};

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
function main(raw) {
    var lines = raw.trim().split("\n").map(function (l) { return l.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var _a = __read(lines.shift(), 3), n = _a[0], m = _a[1], k = _a[2];
    var as = lines.shift();
    var bs = lines.shift();
    // let [n, m, k] = [40000, 40000, Math.ceil(Math.random() * 10) * 2];
    // const as = Array.from({ length: n }, (_, i) => i % 2);
    // const bs = Array.from({ length: n }, () => Math.round(Math.random()));
    var count = 0;
    var awhs = new Map();
    ;
    for (var i = 0; i < n; i++) {
        var w = 0;
        while (as[i] === 1 && i < n) {
            i++;
            w++;
        }
        if (w > 0) {
            if (!awhs.has(w)) {
                awhs.set(w, 1);
            }
            else {
                awhs.set(w, awhs.get(w) + 1);
            }
        }
    }
    var _loop_1 = function (j) {
        var h = 0;
        while (bs[j] === 1 && j < m) {
            h++;
            j++;
        }
        if (h > 0) {
            __spread(awhs.entries()).forEach(function (_a) {
                var _b = __read(_a, 2), w = _b[0], t = _b[1];
                // console.log(w, t);
                count += t * countsubRets(w, h, k);
            });
        }
        out_j_1 = j;
    };
    var out_j_1;
    for (var j = 0; j < m; j++) {
        _loop_1(j);
        j = out_j_1;
    }
    console.log(count);
}
var dp = {};
function countsubRets(w, h, k) {
    // if(w * h in dp) {
    //     return dp[w * h];
    // }
    var cnt = 0;
    for (var pw = 1; pw <= w && pw <= k; pw++) {
        // console.log(pw, w, h, k);
        if (k % pw === 0) {
            var desiredH = k / pw;
            if (desiredH <= h) {
                var horz = w - pw + 1;
                var vert = h - desiredH + 1;
                cnt += horz * vert;
            }
        }
    }
    // console.log(cnt);
    // dp[w * h] = cnt;
    return cnt;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

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

let arr = ''
let ptr = 0
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

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

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a) {
  return parseInt(a[ptr++])
}

function readString(a) {
  return a[ptr++]
}

function readStrings(a) {
  return a[ptr++].split(' ')
}

function readInts(a) {
  return a[ptr++].split(' ').map(a => parseInt(a))
}

function main(input) {
  const [n, m, k] = readInts(input)
  const a = readInts(input)
  const b = readInts(input)
  const aS = seg(a)
  const bS = seg(b)
  let ans = 0
  for(let i = 1, len = aS.length; i < len; i++) {
    if(k % i === 0 && k / i <= m) {
      ans += aS[i] * bS[k / i]
    }
  }
  wr(ans)
}

function seg(a) {
  let i = 0
  const n = a.length
  const map = new Array(n + 1).fill(0)
  while(i < n) {
    if(a[i] === 0) {
      i++
      continue
    }
    let j = i
    while(j < n && a[j] === 1) j++
    for(let k = j - i; k >= 1; k--) map[k] += j - i - k + 1
    i = j
  }
  return map
}

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0 && acc > 0) {
      aNums.push(acc)
      acc = 0
    } else {
      acc++
    }
  }
  if (acc>0) {
    aNums.push(acc)
  }
  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0 && acc > 0) {
      bNums.push(acc)
      acc = 0
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  const sizeArr = []
  for (const num of aNums) {
    for (const bNum of bNums) {
      const s = num * bNum
      if (s >= k) {
        sizeArr.push([num, bNum])
      }
    }
  }
  let sum = 0
  const f =  factors(k).sort((a, b) => a-b)

  for (const [x, y] of sizeArr) {
    // let t1 = 1
    // let t2 = f.reduce((r,x) => r*x, 1)
    for (let j = 0; j < f.length; j++) {

      const t1 = f[j]
      const t2 = k / f[j]
      // console.log(t1, t2)
      if (t1 <= x && t2 <= y) {
        // console.log(t1, t2)
        // console.log(x-t1+1, y-t2+1)
        sum += (x-t1+1) * (y-t2+1)
      }
    }
  }
  console.log(sum)
}

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

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
function main(raw) {
    var lines = raw.trim().split("\n").map(function (l) { return l.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var _a = __read(lines.shift(), 3), n = _a[0], m = _a[1], k = _a[2];
    var as = lines.shift();
    var bs = lines.shift();
    // let [n, m, k] = [40000, 40000, 2];
    // const as = Array.from({ length: n }, (_, i) => i % 3);
    // const bs = Array.from({ length: n }, () => Math.round(Math.random()));
    var count = 0;
    var awhs = new Map();
    ;
    for (var i = 0; i < n; i++) {
        var w = 0;
        while (as[i] === 1 && i < n) {
            i++;
            w++;
        }
        if (w > 0) {
            if (!awhs.has(w)) {
                awhs.set(w, 1);
            }
            else {
                awhs.set(w, awhs.get(w) + 1);
            }
        }
    }
    var _loop_1 = function (j) {
        var h = 0;
        while (bs[j] === 1 && j < m) {
            h++;
            j++;
        }
        if (h > 0) {
            __spread(awhs.entries()).forEach(function (_a) {
                var _b = __read(_a, 2), w = _b[0], t = _b[1];
                // console.log(w, t);
                count += t * countsubRets(w, h, k);
            });
        }
        out_j_1 = j;
    };
    var out_j_1;
    for (var j = 0; j < m; j++) {
        _loop_1(j);
        j = out_j_1;
    }
    console.log(count);
}
var dp = {};
function countsubRets(w, h, k) {
    if (w * h in dp) {
        return dp[w * h];
    }
    var cnt = 0;
    for (var pw = 1; pw <= w && pw <= k; pw++) {
        // console.log(pw, w, h, k);
        if (k % pw === 0) {
            var desiredH = k / pw;
            if (desiredH <= h) {
                var horz = w - pw + 1;
                var vert = h - desiredH + 1;
                cnt += horz * vert;
            }
        }
    }
    // console.log(cnt);
    dp[w * h] = cnt;
    return cnt;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();


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

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

  if (c % 2 === 1) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const obj = {};
  const uniqArr = [...new Set(arr)];

  for (let i = 0; i < uniqArr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (uniqArr[i] <= arr[j]) {
        if (!obj[uniqArr[i]]) {
          obj[uniqArr[i]] = 1;
        }
        else {
          obj[uniqArr[i]]++;
        }
      }
    }
  }

  let ans = 0;

  for (x in obj) {
    const target = Math.min(x, obj[x]);
    ans = Math.max(target, ans);
  }

  console.log(ans);

  c++;
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    solveWrap(inputString);
});

function solve(arr){
	arr.sort((a,b) => b-a);
	let min = 0;
	for (const el of arr) {
		min++;
		if(el<min){
			min--;
			break;
		}
	}
	return min;
}

function solveWrap(input) {
    let inputAr = input.trim().split('\n');
	let k = inputAr.shift();
	for (let i = 0; i < k; i++) {
		inputAr.shift();
		console.log(solve(inputAr.shift().split(' ').map((el) => +el)));
	}
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var list = nextIntArray();
    list.sort(function(a,b){
    	return b - a;
    });
    var max = 0;
    for(var j = 0; j < N; j++){
      if(j + 1 <= list[j]){
        max = j + 1;
      }else{
        break;
      }
      output[i] = max;
    }
  }
  myout(myconv(output, 9));
}

'use strict'

const problem = (n, a) => {
    a = a.sort((x, y) => y - x);
    for (let i = 0; i < a.length; i++) {
        if (a[i] <= i) return i;
    }
    return a.length;
}
let q = +readline();
while(q--) print(problem(+readline(), readline().split(' ').map(Number)))

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
  let ans = [];
  for(let i = 0; i < t; i++){
    let n = nl.num();
    let a = nl.nums();
    a.sort((x, y) => y - x);
    let flag = true;
    for(let j = 0; j < n; j++){
      if (a[j] <= j) {
        ans.push(j);
        flag = false;
        break;
      }
    }
    if (flag) {
      ans.push(n);
    }
  }
	console.log(ans.join('\n'));

};

process.stdin.on('end', sol);


var n = Number(readline());
const map = {
  purple: "Power",
  green: "Time",
  blue: "Space",
  orange: "Soul",
  red: "Reality",
  yellow: "Mind"
};
const colors = new Set(Object.keys(map));
while (n--)
  colors.delete(readline().trim());
print(colors.size);
for (var color of colors)
  print(map[color]);

function answer(input){
    var stones = {
        purple: 'Power',
        green: 'Time',
        blue: 'Space',
        orange: 'Soul',
        red: 'Reality',
        yellow: 'Mind'
    };

    var numStones = readline();
    var inputStones = [];
    var outputStones = [];

    for(var i = 0; i < numStones; i++){
        inputStones.push(readline());
    }

    inputStones.forEach(function(stoneColor){
        delete stones[stoneColor];
    });

    for(var stoneColor in stones){
        outputStones.push(stones[stoneColor]);
    }
    print(outputStones.length);
    outputStones.forEach(function(stone){
        print(stone);
    });
}

answer();

var n = readline().split(" ").map(function(x) { return parseInt(x); });
var s = ""
var obj = {}
for(var i = 0; i < n; i++){
    s = readline()
    switch(s){
        case "purple":
            obj.Power = 1
            break
        case "green":
            obj.Time = 1
            break
        case "blue":
            obj.Space = 1
            break
        case "orange":
            obj.Soul = 1
            break
        case "red":
            obj.Reality = 1
            break
        case "yellow":
            obj.Mind = 1
            break
    }
}
var ans = 0
var ansarr = []
if(!obj.hasOwnProperty("Power")){
    ans += 1
    ansarr.push("Power")
}
if(!obj.hasOwnProperty("Time")){
    ans += 1
    ansarr.push("Time")
}
if(!obj.hasOwnProperty("Space")){
    ans += 1
    ansarr.push("Space")
}
if(!obj.hasOwnProperty("Soul")){
    ans += 1
    ansarr.push("Soul")
}
if(!obj.hasOwnProperty("Reality")){
    ans += 1
    ansarr.push("Reality")
}
if(!obj.hasOwnProperty("Mind")){
    ans += 1
    ansarr.push("Mind")
}
print(ans)
for(var j = 0; j < ansarr.length; j++){
    print(ansarr[j])
}
    // the Power Gem of purple color,
    // the Time Gem of green color,
    // the Space Gem of blue color,
    // the Soul Gem of orange color,
    // the Reality Gem of red color,
    // the Mind Gem of yellow color.

// 2
// Time
// Space

var col2gem = {
    purple: "Power",
    green: "Time",
    blue: "Space",
    orange: "Soul",
    red: "Reality",
    yellow: "Mind",
};

var n = readline();

var seen = new Set();

for (var i = 0; i < n; i++) {
    seen.add(readline());
}

print(6 - n);

for (var col in col2gem) {
    if (!seen.has(col)) {
        print(col2gem[col]);
    }
}

// //The colors of the six gems
var gems = [
    { name: 'Power',    color: 'purple' },
    { name: 'Time',     color: 'green' },
    { name: 'Space',    color: 'blue' },
    { name: 'Soul',     color: 'orange' },
    { name: 'Reality',  color: 'red' },
    { name: 'Mind',     color: 'yellow' }
]
//the number of Gems in Infinity Gauntlet.
var n = readline();
// var n = prompt();
var colors = [];
if ((n > 0 || n == 0) && (n < 6 || n == 6)) {
    for (i = 0; i < n; i++) {
        colors.push(readline())
        // colors.push(prompt())
    }
}
var absent=gems.filter(function(gem){
    return (colors.indexOf(gem.color) == -1);
})
var m=absent.length
print(m)
// console.log(m)
// console.log(colors)
print(...absent.map(absent=>absent.name))
// console.log(...absent.map(absent=>absent.name))

var names = ["purple","green","blue","orange","red","yellow"];
var powers = ["Power","Time","Space","Soul","Reality","Mind"];

var number = +readline();
while(number > 0) {
    powers[names.indexOf(readline())] = 0;
    number --;
}

var results = powers.filter(power => power);
write(results.length + '\n');
results.forEach(result => write(result + '\n'))

  var n = parseInt(readline());
  var m = [];
  m['purple'] = 'Power';
  m['green'] = 'Time';
  m['blue'] = 'Space';
  m['orange'] = 'Soul';
  m['red'] = 'Reality';
  m['yellow'] = 'Mind';
  for(var i = 0; i < n; i += 1) {
    var tmp = readline();
    m[tmp] = '';
  }
  var res = '';
  var count = 0;
  for(var c in m) {
    if(m[c].length > 0) {
      res += m[c] + '\n';
      count += 1;
    }
  }
  print(count);
  print(res);

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var map = {
		purple : "Power",
		green : "Time",
		blue : "Space",
		orange : "Soul",
		red : "Reality",
		yellow : "Mind"
	};
	var N = nextInt();
	for(var i = 0; i < N; i++){
		map[next()] = "";
	}
	var keys = Object.keys(map);
	var output = [];
	for(var i = 0; i < keys.length; i++){
		if(map[keys[i]] != ""){
			output.push(map[keys[i]]);
		}
	}
	myout(output.length);
	myout(myconv(output, 9));
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
const arr = [];
const obj = {
  purple: 'Power',
  green: 'Time',
  blue: 'Space',
  orange: 'Soul',
  red: 'Reality',
  yellow: 'Mind',
};

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

  delete obj[str];

  c++;
});

rl.on('close', () => {
  const ans = Object.values(obj);

  console.log(ans.length);
  for (let i = 0; i < ans.length; i++) {
    console.log(ans[i]);
  }
});

let input = [];

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

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

RL.on('close', () => {
    let n = parseInt(input[0]);
    let data = {
        "red" : [0, 'Reality'],
        "purple": [0, 'Power'],
        "yellow": [0, 'Mind'],
        "orange": [0, 'Soul'],
        "blue": [0, 'Space'],
        "green": [0, 'Time'],
    }

    console.log(6-n);
    if(6-n > 0){
        for(let i = 1; i <= n; i++){
            data[input[i]][0] = 1;
        }

        for(elem in data){
            if(data[elem][0] == 0){
                console.log(data[elem][1]);
            }
        }
    }
});

// http://codeforces.com/contest/987/problem/A
// A. Перчатка бесконечности
'use strict';

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

const gauntletMap = {
  purple: 'Power',
  green: 'Time',
  blue: 'Space',
  orange: 'Soul',
  red: 'Reality',
  yellow: 'Mind',
};

const input = [];
rl.on('line', (line) => { input.push(line); });

rl.on('close', function () {
  for (let i = 1; i < input.length; i++) {
    delete gauntletMap[input[i]];
  }

  console.log(Object.getOwnPropertyNames(gauntletMap).length);
  for (let key in gauntletMap) {
    console.log(gauntletMap[key]);
  }
});

var g = {
    'purple': 'Power',
    'green': 'Time',
    'blue': 'Space',
    'orange': 'Soul',
    'red': 'Reality',
    'yellow': 'Mind',
};
var n = parseInt(readline());
while(n--){
    x = readline();
    delete g[x];
}
print(Object.keys(g).length)
Object.keys(g).forEach((e)=>{
    print(g[e]);
})

function answer(input){
    var stones = {
        purple: 'Power',
        green: 'Time',
        blue: 'Space',
        orange: 'Soul',
        red: 'Reality',
        yellow: 'Mind'
    };

    var numStones = readline();
    var inputStones = [];
    var outputStones = [];
    for(var i = 0; i < numStones; i++){
        inputStones.push(readline());
    }
    inputStones.forEach(function(stoneColor){
        delete stones[stoneColor];
    });
    for(var stoneColor in stones){
        outputStones.push(stoneColor[stoneColor]);
    }
    print(outputStones.length);
    outputStones.forEach(function(stone){
        print(stone);
    });
}

answer();

var col2gem = {
    purple: "Power",
    green: "Time",
    blue: "Space",
    orange: "Soul",
    red: "Reality",
    yellow: "Mind",
};

var n = readline();

var seen = new Set();

for (var i = 0; i < n; i++) {
    seen.add(readline());
}

for (var col in col2gem) {
    if (!seen.has(col)) {
        print(col2gem[col]);
    }
}

// //The colors of the six gems
var gems = [
    { name: 'Power',    color: 'purple' },
    { name: 'Time',     color: 'green' },
    { name: 'Space',    color: 'blue' },
    { name: 'Soul',     color: 'orange' },
    { name: 'Reality',  color: 'red' },
    { name: 'Mind',     color: 'yellow' }
]
//the number of Gems in Infinity Gauntlet.
var n = readline();
// var n = prompt();
var colors = [];
if ((n > 0 || n == 0) && (n < 6 || n == 6)) {
    for (i = 0; i < n; i++) {
        colors.push(readline())
        // colors.push(prompt())
    }
}
var absent=gems.filter(function(gem){
    return (colors.indexOf(gem.color) == -1);
})
var m=absent.length
print(m)
// console.log(m)
// console.log(colors)
print(absent.map(absent=>absent.name))
// console.log(absent.map(absent=>absent.name))

// //The colors of the six gems
var gems = [
    { name: 'Power',    color: 'purple' },
    { name: 'Time',     color: 'green' },
    { name: 'Space',    color: 'blue' },
    { name: 'Soul',     color: 'orange' },
    { name: 'Reality',  color: 'red' },
    { name: 'Mind',     color: 'yellow' }
]
//the number of Gems in Infinity Gauntlet.
var n = readline().split(' ');
var colors = [];
var color;
if ((n > 0 || n == 0) && (n < 6 || n == 6)) {
    for (i = 0; i < n; i++) {
        colors.push(readline()+"/n")
    }
}
var absent=gems.filter(function(gem){
    return (colors.indexOf(gem.color) == -1);
})
var m=absent.length
print(m)
print(absent.map(absent=>absent.name))

  var n = parseInt(readline());
  var m = [];
  m['purple'] = 'power';
  m['green'] = 'Time';
  m['blue'] = 'Space';
  m['orange'] = 'Soul';
  m['red'] = 'Reality';
  m['yellow'] = 'Mind';
  for(var i = 0; i < n; i += 1) {
    var tmp = readline();
    m[tmp] = '';
  }
  var res = '';
  var count = 0;
  for(var c in m) {
    if(m[c].length > 0) {
      res += m[c] + '\n';
      count += 1;
    }
  }
  print(count);
  print(res);


"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let str = readline().trim();
    let ans = 9,
      cnt0 = 0,
      cnt1 = 0;
    for (let i = 0; i < 10; i++) {
      if ((i + 1) % 2 === 1) {
        if (str[i] !== "0") cnt0++;
      } else if (str[i] === "1") cnt1++;
      if (cnt0 > cnt1 + Math.floor((10 - i) / 2)) ans = Math.min(ans, i);
      if (cnt1 > cnt0 + Math.floor((9 - i) / 2)) ans = Math.min(ans, i);
    }
    cnt0 = 0;
    cnt1 = 0;
    for (let i = 0; i < 10; i++) {
      if ((i + 1) % 2 === 1) {
        if (str[i] === "1") cnt0++;
      } else if (str[i] !== "0") cnt1++;
      if (cnt0 > cnt1 + Math.floor((10 - i) / 2)) ans = Math.min(ans, i);
      if (cnt1 > cnt0 + Math.floor((9 - i) / 2)) ans = Math.min(ans, i);
    }
    console.log(ans + 1);
  }
};
solve();

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

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

function main () {
	let t = rn();
	while (t--) {
		let s = rl();

		const winscrt1 = [3, 3, 2, 2];
		const winscrt2 = [3, 2, 2, 1];

		let i, mx = [0, 0], mn = [0, 0];
		for (i = 0; i < 9; i++) {
			const team = i % 2;
			if (s[i] == 1) {
				mx[team]++;
				mn[team]++;
			}
			if (s[i] == '?') {
				mx[team]++;
			}

			let t1rel = mx[0] - mn[1];
			let t2rel = mx[1] - mn[0];

			if (t1rel == winscrt1[i - 5]) break;
			if (t2rel == winscrt2[i - 5]) break;
		}
		ans = i + 1;
		console.log(ans);
	}
}


var nm = readline().split(' ').map(Number);
var n = nm[0];
var m = nm[1];
var p = [];
var sum = 0;
for (var i=0; i<m; i++){
	var s = readline().split(' ').map(Number);
	p[i] = s;
}
for (var i=0; i<n; i++){
	var sum1 = 0;
	var t = 1100;
	for (var j=0; j<m; j++){
		if ( (i+1) >= p[j][0] && (i+1) <= p[j][1] ) {
			if (p[j][2] < t) {
				t = p[j][2];
				sum1 = p[j][3];
			}
		}
	}
	sum += sum1;
}
print (sum);

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let [U] = ipt.split(EOL)[0].split(' ').map(v => parseInt(v))
  let B = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').map(v => parseInt(v)))

  let s = 0
  for (let i = 1; i < U + 1; i++) {
    s += b(i)
  }

  console.log(s)

  function b (u) {
    let bt = Infinity
    let m = 0
    for (let i = 0; i < B.length; i++) {
      const [l, r, t, c] = B[i]
      if (u < l || u > r) continue
      if (t < bt) {
        bt = t
        m = c
      }
    }
    return m
  }
})


let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    let [len, q] = readLine().split(" ").map(Number);
    const str = readLine();
    const queries = [];
    while (q--) {
      const _q = readLine().split(" ").map(Number);
      queries.push(_q);
    }
    let [store, c0, c1] = [[], 0, 0];
    for (let i = 0; i < len; i++) {
      const n = str[i];
      if (n === "0") c0++;
      else c1++;
      store[i] = { c0, c1 };
    }
    for (let [start, end] of queries) {
      if (
        (str[start - 1] === "0" && store[start - 1].c0 > 1) ||
        (str[start - 1] === "1" && store[start - 1].c1 > 1) ||
        (str[end - 1] === "0" && Math.abs(store[end - 1].c0 - store[len - 1].c0) >= 1) ||
        (str[end - 1] === "1" && Math.abs(store[end - 1].c1 - store[len - 1].c1) >= 1)
      ) {
        console.log(`YES`);
      } else console.log(`NO`);
    }
  }
}

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,q] = ti(readline().split(' '));
        let s = readline().split('');
        for(let i = 0; i < q; i++){
            let [l,r] = ti(readline().split(' '));
            l -= 1;
            r -= 1;
            let cr = s[r];
            let cl = s[l];
            let flag = false;
            for(let j = r+1; j < n; j++){
                if(s[j] === cr){
                    flag = true;
                    break;
                }
            }

            if(!flag){
                for(let j = 0; j < l; j++){
                    if(s[j] === cl){
                        flag = true;
                        break;
                    }
                }
            }

            if(flag)
                console.log('YES');
            else
                console.log('NO');
        }
    }
}


var input = readline().split(' ');
var n = parseInt(input[0]), m=parseInt(input[1]), k=parseInt(input[2]);
for(var i=1; i<=n; i++) readline();
var answer = ''+m*(m-1)/2+'\n';
for(var i=1; i<=m; i++)
{
for(var j=i+1; j<=m; j++)
{
answer+=k?j+' '+i+'\n':i+' '+j+'\n';
}
}
print(answer);

var l=readline().split(' ');
var n=+l[0];
var m=+l[1];
var k=+l[2];
var a=[];
for(var i=0;i<n;i++){
	a[i]=readline().split(' ').map(function(v){return +v});
}

var ans=[];
if(k){
	for(var ii=m-1;ii>=0;ii--){
		for(var i=0;i<ii;i++){
			var flg=false;
			for(var j=0;j<n;j++){
				var arr=a[j];
				if(arr[i]<arr[i+1]){
					flg=true;
					var temp=arr[i];
					arr[i]=arr[i+1];
					arr[i+1]=temp;
				}
			}
			if(flg){
				ans.push((i+2)+' '+(i+1));
			}
		}
	}
}else{
	for(var ii=m-1;ii>=0;ii--){
		for(var i=0;i<ii;i++){
			var flg=false;
			for(var j=0;j<n;j++){
				var arr=a[j];
				if(arr[i]>arr[i+1]){
					flg=true;
					var temp=arr[i];
					arr[i]=arr[i+1];
					arr[i+1]=temp;
				}
			}
			if(flg){
				ans.push((i+1)+' '+(i+2));
			}
		}
	}
}
print(ans.length);
for(var i=0;i<ans.length;i++){
	print(ans[i])
}

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 arrayNum = integers[0], count = integers[1], direction = integers[2];

	print(count*(count-1)/2);

	if (direction == 0) {
		for (var i = 1; i <= count; i += 1) {
			for (var j = i+1; j <= count; j += 1) {
				print([i, j].join(' '));
			}
		}
	}
	else {
		for (var i = count; i >= 1; i -= 1) {
			for (var j = i-1; j >= 1; j -= 1) {
				print([i, j].join(' '));
			}
		}
	}
}

main();

var input = readline().split(' ');
var n = parseInt(input[0]), m=parseInt(input[1]), k=parseInt(input[2]);
for(var i=1; i<=n; i++) readline();
var answer = ''+m*(m-1)/2+'\n';
for(var i=1; i<=m; i++)
{
for(var j=i+1; j<=m; j++)
{
answer+=k?i+' '+j+'\n':j+' '+i+'\n';
}
}
print(answer);


// n = 7;
// k = 4;
// inp_str = '4727447';

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
			//console.log('i=',i);
				if ( (i+1) % 2 == 0){
					//console.log('i=5',str);
					if (i-1>=0 && str[i-1]=='4'){
						if ( (j%2==0) != (k%2 == 0)){
							str = str.replaceAt(i,'7');
							//console.log('aa=',str);
						}
						//console.log('aa=',str);
						return str;
					}
					//console.log(str);
					str = str.replaceAt(i,'7');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i--;
				}
				else{
					if (i+2 < n && str[i+2]=='7'){
						if ( (j%2==0) != (k%2 == 0)){
							str = str.replaceAt(i+1,'4');
						}
						return str;
					}

					str = str.replaceAt(i+1,'4');
					//if (i-1 >=0) i= i - 2;
					//if (i < n - 2) i--;
					i++;
				}
				j++;
				//console.log('j=',j);
				//console.log('str=',str);
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
//print(k,' ',n);
//console.log(transform(inp_str, k));
print(transform(inp_str, k));

var input = readline().split('\n');
line1 = input[0].split(' ');
n = line1[0];
k = line1[1];
inp_str = input[1];

//n = 7;
//k = 4;
//inp_str = '4727447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					//console.log(str);
					str = str.replaceAt(i+1,'4');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i++;
				}
				else{
					str = str.replaceAt(i,'7');
					//if (i-1 >=0) i= i - 2;
					if (i < n - 2) i--;
				}
				j++;
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
print(input[1]);
print(input[0]);
print(input);
//print(k,' ',n);
//console.log(transform(inp_str, k));
//print(transform(inp_str, k));

var input = readline().split('\n');
line1 = input[0].split(' ');
n = line1[0];
k = line1[1];
inp_str = input[1];

//n = 7;
//k = 4;
//inp_str = '4727447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					//console.log(str);
					str = str.replaceAt(i+1,'4');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i++;
				}
				else{
					str = str.replaceAt(i,'7');
					//if (i-1 >=0) i= i - 2;
					if (i < n - 2) i--;
				}
				j++;
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
print(input[1]);
print(input[0]);
//print(k,' ',n);
//console.log(transform(inp_str, k));
//print(transform(inp_str, k));

var input = readline().split('\n');
line1 = input[0].split(' ');
n = line1[0];
k = line1[1];
inp_str = input[1];

//n = 7;
//k = 4;
//inp_str = '4727447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					//console.log(str);
					str = str.replaceAt(i+1,'4');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i++;
				}
				else{
					str = str.replaceAt(i,'7');
					//if (i-1 >=0) i= i - 2;
					if (i < n - 2) i--;
				}
				j++;
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
print(input[1]);
print(k,' ',n);
//console.log(transform(inp_str, k));
//print(transform(inp_str, k));

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

//n = 3;
//k = 1000000000;
//inp_str = '447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					if (i-1>=0 && str[i-1]=='4'){
						if ( (j%2==0 ^ k%2 == 0) ==1){
							str = str.replaceAt(i,'7');
						}
						return str;
					}
					//console.log(str);
					str = str.replaceAt(i,'7');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i--;
				}
				else{

					if (i+2 < n && str[i+2]=='7'){
						if ( (j%2==0 ^ k%2 == 0) ==1){
							str = str.replaceAt(i+1,'4');
						}
						return str;
					}

					str = str.replaceAt(i+1,'4');
					//if (i-1 >=0) i= i - 2;
					//if (i < n - 2) i--;
					i++;
				}
				j++;
				//console.log('j=',j);
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
//print(k,' ',n);
//console.log(transform(inp_str, k));
print(transform(inp_str, k));

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

//n = 3;
//k = 1000000000;
//inp_str = '447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					if (i+2 < n && str[i+2]=='7'){
						if ( (j%2==0 ^ k%2 == 0) ==1){
							str = str.replaceAt(i,'7');
						}
						return str;
					}
					//console.log(str);
					str = str.replaceAt(i+1,'4');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i++;
				}
				else{
					if (i-1>=0 && str[i-1]=='4'){
						if ( (j%2==0 ^ k%2 == 0) ==1){
							str = str.replaceAt(i+1,'4');
						}
						return str;
					}

					str = str.replaceAt(i,'7');
					//if (i-1 >=0) i= i - 2;
					//if (i < n - 2) i--;
					i--;
				}
				j++;
				//console.log('j=',j);
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
//print(k,' ',n);
//console.log(transform(inp_str, k));
print(transform(inp_str, k));

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

//n = 7;
//k = 4;
//inp_str = '4727447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					//console.log(str);
					str = str.replaceAt(i+1,'4');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i++;
				}
				else{
					str = str.replaceAt(i,'7');
					//if (i-1 >=0) i= i - 2;
					if (i < n - 2) i--;
				}
				j++;
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
//print(k,' ',n);
//console.log(transform(inp_str, k));
print(transform(inp_str, k));

// n = 7;
// k = 4;
// inp_str = '4727447';

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
			//console.log('i=',i);
				if ( (i+1) % 2 == 0){
					//console.log('i=5',str);
					if (i-1>=0 && str[i-1]=='4'){
						if ( (j%2==0) == (k-1%2 == 0)){
							str = str.replaceAt(i,'7');
							//console.log('aa=',str);
						}
						//console.log('aa=',str);
						return str;
					}
					//console.log(str);
					str = str.replaceAt(i,'7');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i--;
				}
				else{
					if (i+2 < n && str[i+2]=='7'){
						if ( (j%2==0) != (k-1%2 == 0)){
							str = str.replaceAt(i+1,'4');
						}
						return str;
					}

					str = str.replaceAt(i+1,'4');
					//if (i-1 >=0) i= i - 2;
					//if (i < n - 2) i--;
					i++;
				}
				j++;
				//console.log('j=',j);
				//console.log('str=',str);
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
//print(k,' ',n);
//console.log(transform(inp_str, k));
print(transform(inp_str, k));

// n = 7;
// k = 4;
// inp_str = '4727447';

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
			//console.log('i=',i);
				if ( (i+1) % 2 == 0){
					//console.log('i=5',str);
					if (i-1>=0 && str[i-1]=='4'){
						if ( (j%2==0) == (k%2 == 0)){
							str = str.replaceAt(i,'7');
							//console.log('aa=',str);
						}
						//console.log('aa=',str);
						return str;
					}
					//console.log(str);
					str = str.replaceAt(i,'7');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i--;
				}
				else{
					if (i+2 < n && str[i+2]=='7'){
						if ( (j%2==0) != (k%2 == 0)){
							str = str.replaceAt(i+1,'4');
						}
						return str;
					}

					str = str.replaceAt(i+1,'4');
					//if (i-1 >=0) i= i - 2;
					//if (i < n - 2) i--;
					i++;
				}
				j++;
				//console.log('j=',j);
				//console.log('str=',str);
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
//print(k,' ',n);
//console.log(transform(inp_str, k));
print(transform(inp_str, k));

var input = readline().split(' ');
n = input[0];
k = input[1];
var inp_str = readline();

//n = 7;
//k = 4;
//inp_str = '4727447';

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

function transform(str, k){
	//for (i = 0; i < str.length; i ++)
	i = 0;
	j = 0;
	//while (j < k){
		while (i < n - 1 && j < k){
			//console.log('i=',i);
			if (str[i] == '4' && str[i+1] == '7'){
				if (i % 2 == 0){
					//console.log(str);
					str = str.replaceAt(i+1,'4');
					//console.log(str[i+1]);
					//console.log('i=',i);
					i++;
				}
				else{
					str = str.replaceAt(i,'7');
					//if (i-1 >=0) i= i - 2;
					if (i < n - 2) i--;
				}
				j++;
			}
			else i++;
		}
		//if (i == str.length) return str;
		//k++;
	//}
	return str;
}
print(input[1]);
print(input[0]);
print(input);
//print(k,' ',n);
//console.log(transform(inp_str, k));
//print(transform(inp_str, k));


//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var x1 = one[0];
		var y1 = one[1];
		var x2 = one[2];
		var y2 = one[3];
		if(x1 == x2){
			output[i] = Math.abs(y1 - y2);
		}else if(y1 == y2){
			output[i] = Math.abs(x1 - x2);
		}else{
			output[i] = Math.abs(y1 - y2) + Math.abs(x1 - x2) + 2;
		}
	}
	myout(myconv(output, 9));
}

const solve = (data) => {
    let x1 = data[0][0];
    let y1 = data[0][1];
    let x2 = data[0][2];
    let y2 = data[0][3];
    if (y1 == y2) {
        if (x1 == x2) {
            return 0;
        } else {
            return Math.abs(x2 - x1);
        }
    } else {
        if (x1 == x2) {
            return Math.abs(y2 - y1);
        } else {
            let h = Math.abs(x2 - x1);
            let v = Math.abs(y2 - y1);
            return h + 2 + v;
        }
    }
};

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

};

main()

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));
	var dist = 0;
	if(!(params[0]===params[2] || params[1]===params[3])) {
		dist+=2;}
	dist+=Math.abs(params[0]-params[2]) + Math.abs(params[1]-params[3]);
	print(dist);

}

/* Description probleme et solution
......
..Problem.....
A. Box is Pull
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x1,y1) to the point  (x2,y2)

He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by 1 unit.

For example, if the box is at the point (1,2) and Wabbit is standing at the point (2,2), he can pull the box right by 1 unit, with the box ending up at the point (2,2) and Wabbit ending at the point (3,2).

Also, Wabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly 1 unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.

Wabbit can start at any point. It takes 1 second to travel 1 unit right, left, up, or down, regardless of whether he pulls the box while moving.

Determine the minimum amount of time he needs to move the box from (x1,y1) to (x2,y2). Note that the point where Wabbit ends up at does not matter.

Input
Each test contains multiple test cases. The first line contains a single integer t (1≤t≤1000): the number of test cases. The description of the test cases follows.

Each of the next t lines contains four space-separated integers x1,y1,x2,y2 (1≤x1,y1,x2,y2≤109), describing the next test case.

Output
For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from (x1,y1) to (x2,y2).

Example
inputCopy
2
1 2 2 2
1 1 2 2
outputCopy
1
4

Note
In the first test case, the starting and the ending points of the box are (1,2) and (2,2) respectively. This is the same as the picture in the statement. Wabbit needs only 1 second to move as shown in the picture in the statement.

In the second test case, Wabbit can start at the point (2,1). He pulls the box to (2,1) while moving to (3,1). He then moves to (3,2) and then to (2,2) without pulling the box. Then, he pulls the box to (2,2) while moving to (2,3). It takes 4 seconds.

.......

....Solution...
......

Fin Description */

//definition des variables
var testCasesNumber = readline();
var listOfPoints = [];
var minX=0;
var maxX=0;
var minY=0;
var maxY=0;

//Saisie des données

for (var i = 0; i < testCasesNumber; i++) {
    listOfPoints.push(readline().split(' '));
    }
//Traitement ==> calcul du temps minimal requis
for (var i = 0; i < testCasesNumber; i++) {
    minX=Math.min(parseInt(listOfPoints[i][0]),parseInt(listOfPoints[i][2]));
    maxX=Math.max(parseInt(listOfPoints[i][0]),parseInt(listOfPoints[i][2]));
    minY=Math.min(parseInt(listOfPoints[i][1]),parseInt(listOfPoints[i][3]));
    maxY=Math.max(parseInt(listOfPoints[i][1]),parseInt(listOfPoints[i][3]));
    var time = 0;

time =maxX - minX;
time =time + (maxY- minY);
if (minX!=maxX && minY!=maxY){
time+=2;
}
print(time);
}

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

let lineNum = 0;
let countOfData = null;
let data = [];
readline.on('line', line => {
  lineNum++;
  if(lineNum === 1) {
    countOfData = +line;
    return;
  }

  data.push(line.split(' ').map(i => +i));

  if(lineNum - 1 === countOfData) {
    goToSolution(data);
  }

});

function goToSolution(datas) {
  for(let data of datas) {
    let seconds = 0;
    seconds += Math.max(data[0], data[2]) - Math.min(data[0], data[2]);
    seconds += Math.max(data[1], data[3]) - Math.min(data[1], data[3]);
    if(data[0] !== data[2] && data[1] !== data[3]) seconds += 2;
    console.log(seconds);
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    let [x1, y1, x2, y2] = readLine().split(" ").map(Number);
    const [xDiff, yDiff] = [Math.abs(x1 - x2), Math.abs(y1 - y2)];
    const diff = xDiff + yDiff;

    if (xDiff === 0 || yDiff === 0) {
      console.log(diff);
    } else {
      console.log(diff + 2);
    }
  }
}

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

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
})

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 1;
    let i = 1;
    while (i <= testCases) {
      let a = data[i].trim().split(' ').map(Number);
      // const n = data[i] * 1;
      // const k = a[1];
      // let s = data[i + 1].trim().split(' ').map(Number);
      // s.sort((a, b) => b - a);
      let [x1, y1, x2, y2] = a;
      if (x1 === x2 && y1 === y2) {
        console.log(0);
      } else if (x1 === x2) {
        console.log(Math.abs(y1 - y2));
      } else if (y1 === y2) {
        console.log(Math.abs(x1 - x2));
      } else {
        console.log(Math.abs(x1 - x2) + Math.abs(y1 - y2) + 2);
      }
      i += 1;
    }
}

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

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

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

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

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

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

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

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }
// alpha = "abcdefghijklmnopqrstuvwxyz"

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math,
    bi = BigInt, rand = n => Math.random() * n | 0;

  let t = $()
  while (t--) {
    let [x1, y1, x2, y2] = $(4);
    if (x1 == x2 || y1 == y2) log(abs(x2 - x1) + abs(y2 - y1));
    else log(abs(x2 - x1) + abs(y2 - y1) + 2);
  }
}

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

function read() {
  return lines[index++];
}

function main(){
 let t = Number(read());
  while (t--) {
    let line = read();
    let [x1 , y1, x2, y2] = line.split(' ').map(Number);
    if (x1 === x2 && y1 === y2) {
      console.log('0')
    } else {
      console.log(Math.abs(x1 - x2) + Math.abs(y1 - y2) + (x1 !== x2 && y1 !== y2 ? 2 : 0))
    }
  }
}

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 => string.trim());

    main();
});

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

function main() {
    const numCases = readLine();
    for (let i = 0; i < numCases; i++) {
        const input = readLine().split(' ');
        if (input[0] === input[2]) {
            console.log(Math.abs(input[1] - input[3]));
        } else if (input[1] === input[3]){
            console.log(Math.abs(input[0] - input[2]));
        } else {
            console.log(Math.abs(input[0] - input[2]) + Math.abs(input[1] - input[3]) + 2);
        }
    }
}

const solve = (data) => {
    let x1 = data[0][0];
    let y1 = data[0][1];
    let x2 = data[0][2];
    let y2 = data[0][3];
    if (y1 == y2) {
        if (x1 == x2) {
            return 0;
        } else {
            return Math.abs(x2 - x1);
        }
    } else {
        if (x1 == x2) {
            return Math.abs(y2 - y1);
        } else {
            let h = Math.abs(x2 - x1) + 1;
            let v = Math.abs(y2 - y1);
            return h + (h - 1) + v;
        }
    }
};

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

};

main()

const solve = (data) => {
    let x1 = data[0][0];
    let y1 = data[0][1];
    let x2 = data[0][2];
    let y2 = data[0][3];
    if (y1 == y2) {
        if (x1 == x2) {
            return 0;
        } else {
            return Math.abs(x2 - x1);
        }
    } else {
        if (x1 == x2) {
            return Math.abs(y2 - y1);
        } else {
            let h = Math.abs(x2 - x1) + 1;
            let v = Math.abs(y2 - y1);
            return h + 3 + v;
        }
    }
};

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

};

main()


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 [n, x] = readline().split(' ').map(num => Number.parseInt(num, 10));
      let d;
      let h;
      let maxD = -1;
      let maxDiff = -1;
      for (let i = 0; i < n; ++i) {
         [d, h] = readline().split(' ').map(num => Number.parseInt(num, 10));
         if (d > maxD) {
            maxD = d;
         }
         if (d - h > 0 && d - h > maxDiff) {
            maxDiff = d - h;
         }
      }
      if (maxD >= x) {
         print(1);
         continue;
      }
      if (maxDiff < 1) {
         print(-1);
      } else {
         print(Math.ceil((x - maxD) / maxDiff) + 1);
      }
   }
}

let stdinArr = [];
const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.on('line', (line) => {
  stdinArr.push(line.trim().split(' ').map((item) => Number(item.trim())));
}).on('close', () => {
  zmeiGorynich(stdinArr);
})

function zmeiGorynich(stdinArr) {
  let queryNum = stdinArr[0][0];
  let curIndex = 1;
  while (queryNum--) {
    let n = stdinArr[curIndex][0];
    let x = stdinArr[curIndex][1];
    let typeArr = stdinArr.slice(curIndex + 1, curIndex + n + 1);
    console.log(singleQuery(x, typeArr));
    curIndex += (n + 1);
  }
}

function singleQuery(x, typeArr) {
  let maxItem = null;
  let maxBlow = 0;
  let maxType = 0;
  let typeArrLen = typeArr.length;
  for( let i = 0; i < typeArrLen; i++) {
    let item = typeArr[i];
    let d = item[0];
    let h = item[1];
    if (x <= d) {
      // 一击毙命
      return 1;
    }
    let cur = x - d + h;
    if (cur < x) {
      maxItem = item;
    }
    let blow = d-h;
    if (blow > 0 && blow > maxBlow) {
      maxBlow = blow;
    }
    maxType = d > maxType ? d : maxType
  }
  if (maxItem === null) {
    return -1;
  }
  // 减少到可以一击毙命
  let count = (x - maxType) / maxBlow;
  return Math.ceil(count) + 1;
}

let lineCount = 0;
let queriesTotal;
let queriesNum = 0;
let isType = false;
let typeArr = [];
let n; // 拥有的技能个数
let x; // 原始头数

/*const readLine = require('./tools');
readLine(str, (line) => {
  singleLine(line, () => {
    console.log('-----end')
  })
});*/

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
rl.on('line', (line) => {
  singleLine(line, () => {
    rl.close();
  })
});

function singleLine(line, close) {
  if (lineCount === 0) {
    queriesTotal = Number(line.trim());
  } else {
    let lines = line.trim().split(' ').map((item) => Number(item.trim()));
    let first = lines[0];
    let second = lines[1];
    if (!isType) {
      n = first;
      x = second;
      isType = true;
    } else {
      typeArr.push({
        d: first,
        h: second
      });
      if (typeArr.length === n) {
        console.log(zmeiGorynich(x, typeArr));
        isType = false;
        typeArr = [];
        queriesNum++;
      }
    }
  }
  if (queriesNum === queriesTotal) {
    close();
  }
  lineCount ++;
}

function zmeiGorynich(x, typeArr) {
  let maxItem = null;
  let maxBlow = 0;
  let maxType = 0;
  let typeArrLen = typeArr.length;
  for( let i = 0; i < typeArrLen; i++) {
    let item = typeArr[i];
    let {d, h} = item;
    if (x <= d) {
      // 一击毙命
      return 1;
    }
    let cur = x - d + h;
    if (cur < x) {
      maxItem = item;
    }
    let blow = d-h;
    if (blow > 0 && blow > maxBlow) {
      maxBlow = blow;
    }
    maxType = d > maxType ? d : maxType
  }
  if (maxItem === null) {
    return -1;
  }

  // 减少到可以一击毙命
  let count = (x - maxType) / maxBlow;
  return Math.ceil(count) + 1;
}

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

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

    while (T --> 0) {
        var input = rdArN();
        var n = input[0];
        var x = input[1];

        var maxD = -Infinity;
        var maxP = -Infinity;
        var maxOPOP = -Infinity;
        for (var i = 0; i < n; ++i) {
            var input = rdArN();
            var d = input[0];
            var h = input[1];

            maxD = Math.max(maxD, d);
            if (maxP < d - h) {
                maxP = d - h;
                maxOPOP = d;
            }
        }

        if (maxD >= x) {
            pr(1);
        } else {
            if (maxP <= 0) {
                pr(-1);
            } else {
                var res1 = Math.ceil((x-maxD)/maxP) + 1;
                var res2 = Math.ceil((x-maxOPOP)/maxP) + 1;
                pr(Math.min(res1, res2))
            }
        }
    }
};

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

let lineCount = 0;
let queriesTotal;
let queriesNum = 0;
let isType = false;
let typeArr = [];
let n; // 拥有的技能个数
let x; // 原始头数

// const readLine = require('./tools');
// readLine(str, (line) => {
//   singleLine(line, () => {
//     console.log('-----end')
//   })
// });

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
rl.on('line', (line) => {
  singleLine(line, () => {
    rl.close();
  })
});

function singleLine(line, close) {
  if (lineCount === 0) {
    queriesTotal = Number(line.trim());
  } else {
    let lines = line.trim().split(' ').map((item) => Number(item.trim()));
    let first = lines[0];
    let second = lines[1];
    if (!isType) {
      n = first;
      x = second;
      isType = true;
    } else {
      typeArr.push({
        d: first,
        h: second
      });
      if (typeArr.length === n) {
        console.log(zmeiGorynich(x, typeArr));
        isType = false;
        typeArr = [];
        queriesNum++;
      }
    }
  }
  if (queriesNum === queriesTotal) {
    close();
  }
  lineCount ++;
}

function zmeiGorynich(x, typeArr) {
  let maxItem = null;
  let maxBlow = 0;
  let maxType = 0;
  typeArr.forEach((item) => {
    let {d, h} = item;

    if (x <= d) {
      // 一击毙命
      return 1;
    }
    let cur = x - d + h;
    if (cur < x) {
      maxItem = item;
    }
    let blow = d-h;
    if (blow > 0 && blow > maxBlow) {
      maxBlow = blow;
    }
    maxType = d > maxType ? d : maxType
  });
  if (maxItem === null) {
    return -1;
  }

  // 减少到可以一击毙命
  let count = (x - maxType) / maxBlow;
  return Math.ceil(count) + 1;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let queriesTotal;
let queriesNum = 0;
let isType = false;
let typeArr = [];
let n;
let x;
rl.on('line', function(line){
  if (lineCount === 0) {
    queriesTotal = Number(line.trim());
  } else {
    let lines = line.trim().split(' ').map((item) => Number(item.trim()));
    let first = lines[0];
    let second = lines[1];
    if (!isType) {
      n = first;
      x = second;
      isType = true;
    } else {
      typeArr.push({
        d: first,
        h: second
      });
      if (typeArr.length === n) {
        console.log(zmeiGorynich(x, typeArr));
        isType = false;
        typeArr = [];
        queriesNum++;
      }
    }
  }
  if (queriesNum === queriesTotal) {
    rl.close();
  }
  lineCount ++;
});

function zmeiGorynich(x, typeArr) {
  let minLast = x;
  let maxItem = null;
  let maxBlow = 0;
  let maxType = 0;
  typeArr.forEach((item) => {
    let {d, h} = item;
    let cur = minLast - d + h;
    if (cur < minLast) {
      minLast = cur;
      maxItem = item;
    }
    let blow = d-h;
    if (blow > 0 && blow > maxBlow) {
      maxBlow = blow;
    }
    maxType = d > maxType ? d : maxType
  });
  if (maxItem === null) {
    return -1;
  }
  if (minLast <= 0) {
    // 一击毙命
    return 1;
  }

  // 减少到可以一击毙命
  let count = (x - maxType) / maxBlow;
  return Math.ceil(count) + 1;
}

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

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

    while (T --> 0) {
        var input = rdArN();
        var n = input[0];
        var x = input[1];

        var maxD = -Infinity;
        var maxP = -Infinity;
        for (var i = 0; i < n; ++i) {
            var input = rdArN();
            var d = input[0];
            var h = input[1];

            maxD = Math.max(maxD, d);
            maxP = Math.max(maxP, d - h);
        }

        if (maxD > x) {
            pr(1);
        } else {
            if (maxP < 0) {
                pr(-1);
            } else {
                x -= maxD;
                pr(Math.ceil(x/maxP) + 1)
            }
        }
    }
};

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

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

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

    while (T --> 0) {
        var input = rdArN();
        var n = input[0];
        var x = input[1];

        var maxD = -Infinity;
        var maxP = -Infinity;
        var maxOPOP = -Infinity;
        for (var i = 0; i < n; ++i) {
            var input = rdArN();
            var d = input[0];
            var h = input[1];

            maxD = Math.max(maxD, d);
            if (maxP < d - h) {
                maxP = d - h;
                maxOPOP = d;
            }
        }

        if (maxD >= x) {
            pr(1);
        } else {
            if (maxP < 0) {
                pr(-1);
            } else {
                var res1 = Math.ceil((x-maxD)/maxP) + 1;
                var res2 = Math.ceil((x-maxOPOP)/maxP) + 1;
                pr(Math.min(res1, res2))
            }
        }
    }
};

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

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

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

    while (T --> 0) {
        var input = rdArN();
        var n = input[0];
        var x = input[1];

        var maxD = -Infinity;
        var maxP = -Infinity;
        var maxOPOP = -Infinity;
        for (var i = 0; i < n; ++i) {
            var input = rdArN();
            var d = input[0];
            var h = input[1];

            maxD = Math.max(maxD, d);
            if (maxP < d - h) {
                maxP = d - h;
                maxOPOP = d;
            }
        }

        if (maxD > x) {
            pr(1);
        } else {
            if (maxP < 0) {
                pr(-1);
            } else {
                var res1 = Math.ceil((x-maxD)/maxP) + 1;
                var res2 = Math.ceil((x-maxOPOP)/maxP) + 1;
                pr(Math.min(res1, res2))
            }
        }
    }
};

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