'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  a = a.map(num => num - 1);
  for (let [k, p] of a.entries()) {
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const queue = [[root, [root]]];
  for (let [u, path] of queue) {
    if (g[u].length === 0) {
      res.push(path.map(num => num + 1));
    } else {
      for (let i = 0; i < g[u].length; i++) {
        const v = g[u][i];
        if (i === 0) {
          path.push(v);
          queue.push([v, path]);
        } else {
          queue.push([v, [v]]);
        }
      }
    }
  }
  let str = [];
  str.push(res.length + '');
  for (let i = 0; i < res.length; i++) {
    str.push(res[i].length + '');
    str.push(res[i].join(' '));
  }
  console.log(str.join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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

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

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(1);
      console.log(1);
      console.log(arr[0]);
      continue;
    }
    let leaf = {};
    for (let i = 0; i < n; i++) leaf[arr[i]] = 1;
    let path = [],
      vis = new Array(n + 1).fill(0);
    for (let i = 1; i <= n; i++) {
      if (leaf[i]) continue;
      let ans = [],
        v = i;
      while (!vis[v]) {
        ans.push(v);
        vis[v] = 1;
        v = arr[v - 1];
      }
      path.push(ans);
    }
  let PRINT = path.length+'\n';
  for (let i=0; i<path.length; i++){
    let an = path[i]
    PRINT += an.length+'\n';
    PRINT += an.reverse().join(' ')+'\n'
  }
  console.log(PRINT);

  }
};
solve();

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, p)=>{
    let paths = [];
    let hasChildren = new Array(n).fill(false);
    for (let i = 0; i < n; i++) {
        p[i]--;
        if (i === p[i]) continue;
        hasChildren[p[i]] = true;
    }
    let visited = new Array(n).fill(false);
    for (let i = 0; i < n; i++) {
        if (hasChildren[i]) continue;
        let cur = i;
        let path = [];
        while (!visited[cur]) {
            path.push(cur + 1);
            visited[cur] = true;
            cur = p[cur];
        }
        paths.push(path.reverse());
    }

    let result = '';

    result += `${paths.length}\n`;
    for (let i = 0; i < paths.length; i++) {
        result += `${paths[i].length}\n`;
        result += paths[i].join(' ');
        result += '\n';
    }
    result += '\n';
    process.stdout.write(result);
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        // let [n, k] = ra();
        let p = ra();
        // console.log(`${calc(n, p)}`);
        calc(n, p);
    }
}

const readline = require('readline')

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

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

function solve(n, arr) {
    let r
    const adj = {}
    arr.forEach((p, i) => {
        i++
        if (p === i) {
            r = i
            return
        }
        //
        const a = p
        const b = i
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    const ans = dfs(adj, r, n)
// console.log(ans)
// return
    const map = new Map()
    const output = []
    for (let u = 1; u <= n; u++) {
        const x = ans[u]
        if (map.get(x)) continue
        map.set(x, 1)
        const line = []
        for (let i = x.first; i <= x.last; i++) {
            line.push(x.map[i])
        }
        // output.push(x.length, x.join(' '))
        output.push(x.length, line.join(' '))
    }
    return output.length / 2 + '\n' + output.join('\n')
}
function dfs(adj, r, n) {
    // const stack = [[r, 0, -1]]
    const stack = new Queue()
    stack.push([r, 0, -1])
    const ans = Array(n + 1)
    while (stack.length) {
        const [u, i, p] = stack.map[stack.last]
        // const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            // stack[stack.length - 1][1]++
            stack.map[stack.last][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            let max = 0
            let path
            ;(adj[u] || []).forEach(v => {
                if (v === p) return
                if (ans[v].length > max) {
                    max = Math.max(max, ans[v].length)
                    path = ans[v]
                }
            })
            if (path) {
                path.unshift(u)
                ans[u] = path
            } else {
                // ans[u] = [u]
                ans[u] = new Queue()
                ans[u].push(u)
            }
            stack.pop()
        }
    }
    return ans
}

'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);
    process.exit(0);
  } 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 P = readline().split(' ').map(a=>a-1);
  //LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    print(1);
    return
  }
  let has_child = {};
  for (let i=0; i<n; i++){
    has_child[P[i]] = true;
  }
  let visited = new Array(n+1).fill(0)
  let ans = [];
  for (let i=0; i<n; i++){
    if (!has_child[i] && !visited[i]){
      let path = [];
      let v = i;
      while (!visited[v]){
        path.push(v+1);
        visited[v] = 1;
        v = P[v];
      }
      ans.push(path);
    }
  }
  let PRINT = ans.length+'\n';
  for (let i=0; i<ans.length; i++){
    let an = ans[i]
    PRINT += an.length+'\n';
    PRINT += an.reverse().join(' ')+'\n'
  }
  process.stdout.write(PRINT+'\n');
};

'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);
    process.exit(0);
  } 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 P = readline().split(' ').map(a=>a-1);
  //LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    print(1);
    return
  }
  let has_child = {};
  for (let i=0; i<n; i++){
    has_child[P[i]] = true;
  }
  let visited = new Array(n+1).fill(0)
  let ans = [];
  for (let i=0; i<n; i++){
    if (!has_child[i] && !visited[i]){
      let path = [];
      let v = i;
      while (!visited[v]){
        path.push(v+1);
        visited[v] = 1;
        v = P[v];
      }
      ans.push(path);
    }
  }
  process.stdout.write(ans.length+'\n');
  for (let i=0; i<ans.length; i++){
    let an = ans[i]
    process.stdout.write(an.length+'\n');
    process.stdout.write(an.reverse().join(' ')+'\n')
    //pa(an.reverse());
  }
  process.stdout.write('\n');
};

'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);
    process.exit(0);
  } 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 P = readline().split(' ').map(a=>a-1);
  //LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    print(1);
    return
  }
  let has_child = {};
  for (let i=0; i<n; i++){
    has_child[P[i]] = true;
  }
  let visited = new Array(n+1).fill(0)
  let ans = [];
  for (let i=0; i<n; i++){
    if (!has_child[i] && !visited[i]){
      let path = [];
      let v = i;
      while (!visited[v]){
        path.push(v+1);
        visited[v] = 1;
        v = P[v];
      }
      ans.push(path);
    }
  }
  let PRINT = ans.length+'\n';
  for (let i=0; i<ans.length; i++){
    let an = ans[i]
    PRINT += an.length+'\n';
    PRINT += an.reverse().join(' ')+'\n'
  }
  console.log(PRINT);
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  if (n==1){
    print(1);
    print(1);
    return
  }
  let G = {};
  for (let i=0; i<n; i++){
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an.reverse());
  }
  //print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an.reverse());

  }
  //print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an.reverse());

  }
  print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
    pa(an);

  }
  //print();
};

'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 P = ra().map(p=>p-1);
  LT({n, P});
  // PROCESSING:
  let root;
  let G = {};
  for (let i=0; i<n; i++){
    if (i==P[i])
      root = i;
    if (!G[P[i]]){
      G[P[i]] = [];
    }
    G[P[i]].push(i);
  }
  let visited = new Set();
  let ans = [];
  for (let i=0; i<n; i++){
    if (!G[i] && !visited.has(i)){
      let path = [];
      let v = i;
      while (!visited.has(v)){
        path.push(v+1);
        visited.add(v);
        v = P[v];
      }
      ans.push(path);
    }
  }
  print(ans.length);
  for (let an of ans){
    print(an.length);
     pa(an);

  }
  print();
};

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

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
class graph {
  constructor() {
    this.list = {};
  }
  add(v) {
    if (!this.list[v]) this.list[v] = [];
  }
  addE(v, e) {
    if (this.list[v]) this.list[v].push(e);
  }
}
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(1);
      console.log(1);
      console.log(arr[0]);
      continue;
    }
    let g = new graph();
    for (let i = 0, j = 1; i < n; i++, j++) {
      g.add(arr[i]);
      if (arr[i] !== j) g.addE(arr[i], j);
    }
    let path = [],
      res = [];
    const dfs = (g) => {
      let visted = {};
      const helper = (v) => {
        path.push(v);
        if (g.list[v] === undefined) {
          let narr = [];
          for (let i = 0; i < path.length; i++) {
            if (visted[path[i]] === undefined) {
              narr.push(path[i]);
              visted[path[i]] = 1;
            }
          }
          res.push(narr);
          return;
        }
        let arr = g.list[v];
        for (let i = 0; i < arr.length; i++) {
          helper(arr[i]);
          path.pop();
        }
      };
      helper(arr[0]);
    };
    dfs(g);
    console.log(res.length);
    for (let i = 0; i < res.length; i++) {
      console.log(res[i].length);
      console.log(res[i].join(" "));
    }
  }
};
solve();

'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  const g = Array.from({
    length: n + 1
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    if (k + 1 === p) {
      root = p;
    } else {
      g[p].push(k + 1);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path);
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = [];
  str.push(res.length + '');
  for (let i = 0; i < res.length; i++) {
    str.push(res[i].length + '');
    str.push(res[i].join(' '));
  }
  console.log(str.join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    p--;
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path.map(num => num + 1));
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = [];
  str.push(res.length + '');
  for (let i = 0; i < res.length; i++) {
    str.push(res[i].length + '');
    str.push(res[i].join(' '));
  }
  console.log(str.join('\n'));
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    p--;
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path.map(num => num + 1));
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = res.length + '\n';
  for (let i = 0; i < res.length; i++) {
    str += res[i].length + '\n';
    str += res[i].join(' ') + '\n';
  }
  console.log(str);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  let root = -1;
  for (let [k, p] of a.entries()) {
    p--;
    if (k === p) {
      root = p;
    } else {
      g[p].push(k);
    }
  }
  let res = [];
  const dfs = (i, path = []) => {
    path.push(i);
    if (g[i].length === 0) {
      res.push(path.map(num => num + 1));
      return;
    }
    for (let j = 0; j < g[i].length; j++) {
      if (j === 0) {
        dfs(g[i][j], path);
      } else {
        dfs(g[i][j]);
      }
    }
  };
  dfs(root);
  let str = res.length + '\n';
  console.log(res.length);
  for (let i = 0; i < res.length; i++) {
    str += res[i].length + '\n';
    str += res[i].join(' ') + '\n';
  }
  console.log(str);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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


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, p] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        // console.log(solve(n, p, arr), solve2(n, p, arr))
        output[i] = Math.min(solve(n, p, arr.slice()), solve2(n, p, arr.slice()))
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
    return p - c
}
function solve2(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = p - last // last -> p
    let ans = c
    if (last + c >= p) {
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        let x = last
        while (x > 0 && map[x]) {
            // if (!x) x = p
            x--
            // c++
        }
        ans += x
    }
    // console.log('fake', c, ans)
    return ans
}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, p] = rns(),
        a = rns();
  let b = a[n - 1],
      set = new Set(a);
  let t = -1;
  for (let i = b; i >= 0; i--) {
    if (set.has(i)) continue;
    t = i;
    break;
  }
  if (t === -1) {
    for (let i = p - 1; i >= b; i--) {
      if (set.has(i)) continue;
      t = i;
      break;
    }
    if (t === -1) return 0;
    return t - b;
  } else {
    let res = p - b;
    set.add(0);
    for (let j = n - 2; j >= 0; j--) {
      if (a[j] === p - 1) continue;
      set.add(a[j] + 1);
      for (let i = t; i >= 0; i--) {
        if (set.has(i)) continue;
        return res + i;
      }
      return res;
    }
    set.add(1);
    for (let i = t; i >= 0; i--) {
      if (set.has(i)) continue;
      return res + i;
    }
    return res;
  }
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

const readline = require('readline')

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

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
    return p - c
}
function solve2(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = p - last // last -> p
    let ans = c
    if (last + c >= p) {
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        let x = last
        while (x > 0 && map[x]) {
            // if (!x) x = p
            x--
            // c++
        }
        ans += x
    }
    // console.log('fake', c, ans)
    return ans
}

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

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
let r1 = p - c
    let fake = 0
    if (last + c >= p) {
        //
    } else {
        fake = p - (last + c)
        c = p - last
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            if (++arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
let r2 = fake + p - c
        // console.log(arr, fake, r2)
    return Math.min(r1, r2)
    // let max = 0
    // for (let i = 0; i < n - 1; i++) {
    //     if (arr[i] < last && arr[i] > max) {
    //         max = arr[i]
    //     }
    // }
    // return [n, p, arr]
}

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

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            if (++arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
        // console.log(arr)
    return p - c
    // let max = 0
    // for (let i = 0; i < n - 1; i++) {
    //     if (arr[i] < last && arr[i] > max) {
    //         max = arr[i]
    //     }
    // }
    // return [n, p, arr]
}


var n = parseInt(readline());
var a = new Array();
var x = new Array();
var y = new Array();
var bx = new Array();
var by = new Array();
var d = new Array();
var ans = -1;
var tt = 0;
for(var i=0;i<4;i++)
{
    a[i] = new Array();
	x[i] = new Array();
	y[i] = new Array();
	d[i] = new Array();

	for(var j=0;j<4;j++)
	{
	    x[i][j]=new Array();
		y[i][j]=new Array();
	}
}
while(n--)
{
    ans = -1;
	tt = 0;
    for(var i=0;i<4;i++)
	{
        var str = readline().split(' ');
	    for(var j=0;j<4;j++)
		{
		    a[i][j]=parseInt(str[j]);
		}
		var l = a[i][0] - a[i][2];
		var s = a[i][1] - a[i][3];
		x[i][0] = a[i][2]+l;
		y[i][0] = a[i][3]+s;
		x[i][1] = a[i][2]-s;
		y[i][1] = a[i][3]+l;
		x[i][2] = a[i][2]-l;
		y[i][2] = a[i][3]-s;
		x[i][3] = a[i][2]+s;
		y[i][3] = a[i][3]-l;
	}
	gao(0);
	print(ans);
}

function gao(k)
{
    if(ans!=-1&&tt>=ans)
	{
	    return;
	}
	if(k==4)
	{
	    if(isCube())
		{
			if(ans==-1||tt<ans)
			{
				ans = tt;
			}
		}
		return;
	}
    for(var i=0;i<4;i++)
	{
	    bx[k]=x[k][i];
		by[k]=y[k][i];
		tt+=i;
		gao(k+1);
		tt-=i;
	}
}

function isCube()
{
    for(var i=0;i<4;i++)
	{
	    for(j=0;j<4;j++)
		{
		    d[i][j]=(bx[i]-bx[j])*(bx[i]-bx[j])+(by[i]-by[j])*(by[i]-by[j]);
		}
		d[i].sort(sortNum);
	}
	for(var i=0;i<4;i++)
	{
	    if(d[i][1]!=d[i][2]||d[i][3]!=2*d[i][2]||d[i][3]==0)
		{
		    return false;
		}
		if(i!=0&&d[i][1]!=d[i-1][1])
		{
		    return false;
		}
	}
	return true;
}

function sortNum(a, b)
{
    return a-b;
}

;(function () {

	function Rotate(point, center, angine) {
		return {
			x: Math.round(center.x + (point.x - center.x) * Math.cos(angine) - (point.y - center.y) * Math.sin(angine)),
			y: Math.round(center.y + (point.y - center.y) * Math.cos(angine) + (point.x - center.x) * Math.sin(angine))
		};
	}

	function distance (pointA, pointB) {
		return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
	}

	function isSomeOne (a, b, c, d) {
		if (a.x === b.x && a.y === b.y) return true;
		if (a.x === c.x && a.y === c.y) return true;
		if (a.x === d.x && a.y === d.y) return true;
		if (b.x === c.x && b.y === c.y) return true;
		if (b.x === d.x && b.y === d.y) return true;
		if (c.x === d.x && c.y === d.y) return true;
		return false;
	}

	function isSquare (a, b, c, d) {
		var ab = distance(a, b),
			ac = distance(a, c),
			ad = distance(a, d),
			bc = distance(b, c),
			bd = distance(b, d),
			cd = distance(c, d);

		var map = {};
		[ab, ac, ad, bc, bd, cd].forEach(function (e) { map[e] = map[e] ? map[e] + 1 : 1; });

		var flag = false;
		for (var key in map) {
			if (map[key] === 4 && key !== 0) {
				flag = true;
			}
		}

		if (flag) {
			for (var key in map) {
				if (map[key] === 2 && key !== 0) {
					return true;
				}
			}
		}

		return false;
	}

	print(function (n) {

		var answers = [];

		while (n--) answers.push(function () {

			var regiment = [];
			for (var i = 0; i < 4; i++) {
				var newRegiment = readline().split(' ').map(Number);
				regiment.push(newRegiment);
			}

			var moles = [], homes = [];
			for (var i = 0; i < 4; i++) {

				var newMole = {
					x: regiment[i][0],
					y: regiment[i][1]
				};

				var newHome = {
					x: regiment[i][2],
					y: regiment[i][3]
				};

				moles.push(newMole);
				homes.push(newHome);
			}

			var squares = [];
			for (var rotate_1 = 0; rotate_1 < 4; rotate_1++)
				for (var rotate_2 = 0; rotate_2 < 4; rotate_2++)
					for (var rotate_3 = 0; rotate_3 < 4; rotate_3++)
						for (var rotate_4 = 0; rotate_4 < 4; rotate_4++) {
							var mole1 = Rotate(moles[0], homes[0], Math.PI / 2 * rotate_1),
								mole2 = Rotate(moles[1], homes[1], Math.PI / 2 * rotate_2),
								mole3 = Rotate(moles[2], homes[2], Math.PI / 2 * rotate_3),
								mole4 = Rotate(moles[3], homes[3], Math.PI / 2 * rotate_4);

							var differences = isSomeOne(mole1, mole2, mole3, mole4) === false,
								square = isSquare(mole1, mole2, mole3, mole4);
							if (differences && square) {
								squares.push(rotate_1 + rotate_2 + rotate_3 + rotate_4);
							}
						}

			if (squares.length === 0) return -1;
			else if (squares.length === 1) return squares[0];
			else return Math.min.apply(null, squares);

		}());

		return answers.join('\n');

	}(+readline()));

}.call(this));

;(function () {

	print(function (n) {

		var answer = [];

		while (n--) {
			var regiment = [
				readline().split(' ').map(Number),
				readline().split(' ').map(Number),
				readline().split(' ').map(Number),
				readline().split(' ').map(Number)
			];

			var deviation = [
				[regiment[0][0] - regiment[0][2], regiment[0][1] - regiment[0][3]],
				[regiment[1][0] - regiment[1][2], regiment[1][1] - regiment[1][3]],
				[regiment[2][0] - regiment[2][2], regiment[2][1] - regiment[2][3]],
				[regiment[3][0] - regiment[3][2], regiment[3][1] - regiment[3][3]]
			];

			var posiblePositions = [
				[
					[regiment[0][0],   regiment[0][1]],
					[regiment[0][2] - deviation[0][1], regiment[0][3] + deviation[0][0]],
					[regiment[0][2] - deviation[0][0], regiment[0][3] - deviation[0][1]],
					[regiment[0][2] + deviation[0][1], regiment[0][3] - deviation[0][0]]
				],
				[
					[regiment[1][0],   regiment[1][1]],
					[regiment[1][2] - deviation[1][1], regiment[1][3] + deviation[1][0]],
					[regiment[1][2] - deviation[1][0], regiment[1][3] - deviation[1][1]],
					[regiment[1][2] + deviation[1][1], regiment[1][3] - deviation[1][0]]
				],
				[
					[regiment[2][0],   regiment[2][1]],
					[regiment[2][2] - deviation[2][1], regiment[2][3] + deviation[2][0]],
					[regiment[2][2] - deviation[2][0], regiment[2][3] - deviation[2][1]],
					[regiment[2][2] + deviation[2][1], regiment[2][3] - deviation[2][0]]
				],
				[
					[regiment[3][0],   regiment[3][1]],
					[regiment[3][2] - deviation[3][1], regiment[3][3] + deviation[3][0]],
					[regiment[3][2] - deviation[3][0], regiment[3][3] - deviation[3][1]],
					[regiment[3][2] + deviation[3][1], regiment[3][3] - deviation[3][0]]
				]
			];

			var posibleSquare = [];
			for (var i = 0; i < 4; i++)
				for (var j = 0; j < 4; j++)
					for (var k = 0; k < 4; k++)
						for (var l = 0; l < 4; l++) {
							var position_i = posiblePositions[0][i],
								position_j = posiblePositions[1][j],
								position_k = posiblePositions[2][k],
								position_l = posiblePositions[3][l];

							var side_ij = Math.sqrt(Math.pow(position_i[0] - position_j[0], 2) + Math.pow(position_i[1] - position_j[1], 2)),
								side_ik = Math.sqrt(Math.pow(position_i[0] - position_k[0], 2) + Math.pow(position_i[1] - position_k[1], 2)),
								side_il = Math.sqrt(Math.pow(position_i[0] - position_l[0], 2) + Math.pow(position_i[1] - position_l[1], 2));

							if (side_ij === side_ik) {
								var side_lj = Math.sqrt(Math.pow(position_l[0] - position_j[0], 2) + Math.pow(position_l[1] - position_j[1], 2)),
									side_kl = Math.sqrt(Math.pow(position_k[0] - position_l[0], 2) + Math.pow(position_k[1] - position_l[1], 2));

								if (side_ij === side_lj && side_ij === side_kl && side_ij !== 0) {
									if ((position_i[0] === position_j[0] && position_i[1] === position_j[1]) ||
									   (position_i[0] === position_k[0] && position_i[1] === position_k[1]) ||
									   (position_i[0] === position_l[0] && position_i[1] === position_l[1]) ||
									   (position_j[0] === position_k[0] && position_j[1] === position_k[1]) ||
									   (position_j[0] === position_l[0] && position_j[1] === position_l[1]) ||
									   (position_k[0] === position_l[0] && position_k[1] === position_l[1])) {}
									else posibleSquare.push(i + j + k + l);
								}
							} else if (side_ij === side_il) {
								var side_jk = Math.sqrt(Math.pow(position_j[0] - position_k[0], 2) + Math.pow(position_j[1] - position_k[1], 2)),
									side_kl = Math.sqrt(Math.pow(position_k[0] - position_l[0], 2) + Math.pow(position_k[1] - position_l[1], 2));

								if (side_ij === side_jk && side_ij === side_kl && side_ij !== 0) {
									if ((position_i[0] === position_j[0] && position_i[1] === position_j[1]) ||
									   (position_i[0] === position_k[0] && position_i[1] === position_k[1]) ||
									   (position_i[0] === position_l[0] && position_i[1] === position_l[1]) ||
									   (position_j[0] === position_k[0] && position_j[1] === position_k[1]) ||
									   (position_j[0] === position_l[0] && position_j[1] === position_l[1]) ||
									   (position_k[0] === position_l[0] && position_k[1] === position_l[1])) {}
									else posibleSquare.push(i + j + k + l);
								}
							} else if (side_ik === side_il) {
								var side_jl = Math.sqrt(Math.pow(position_j[0] - position_l[0], 2) + Math.pow(position_j[1] - position_l[1], 2)),
									side_kj = Math.sqrt(Math.pow(position_k[0] - position_j[0], 2) + Math.pow(position_k[1] - position_j[1], 2));

								if (side_ik === side_jl && side_ik === side_kj && side_ik !== 0) {
									if ((position_i[0] === position_j[0] && position_i[1] === position_j[1]) ||
									   (position_i[0] === position_k[0] && position_i[1] === position_k[1]) ||
									   (position_i[0] === position_l[0] && position_i[1] === position_l[1]) ||
									   (position_j[0] === position_k[0] && position_j[1] === position_k[1]) ||
									   (position_j[0] === position_l[0] && position_j[1] === position_l[1]) ||
									   (position_k[0] === position_l[0] && position_k[1] === position_l[1])) {}
									else posibleSquare.push(i + j + k + l);
								}
							}
						}

			if (posibleSquare.length === 0) answer.push(-1);
			else if(posibleSquare.length === 1) answer.push(posibleSquare[0]);
			else answer.push(Math.min.apply(null, posibleSquare));
		}

		return answer.join('\n');

	}(+readline()));

}.call(this));

;(function () {

	function Rotate(point, center, angine) {
		return {
			x: Math.round(center.x + (point.x - center.x) * Math.cos(angine) - (point.y - center.y) * Math.sin(angine)),
			y: Math.round(center.y + (point.y - center.y) * Math.cos(angine) + (point.x - center.x) * Math.sin(angine))
		};
	}

	function distance (pointA, pointB) {
		return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
	}

	function isSomeOne (a, b, c, d) {
		if (a.x === b.x && a.y === b.y) return true;
		if (a.x === c.x && a.y === c.y) return true;
		if (a.x === d.x && a.y === d.y) return true;
		if (b.x === c.x && b.y === c.y) return true;
		if (b.x === d.x && b.y === d.y) return true;
		if (c.x === d.x && c.y === d.y) return true;
		return false;
	}

	function isSquare (a, b, c, d) {
		var ab = distance(a, b),
			ac = distance(a, c),
			ad = distance(a, d),
			bc = distance(b, c),
			bd = distance(b, d),
			cd = distance(c, d);

		var map = {};
		[ab, ac, ad, bc, bd, cd].forEach(function (e) { map[e] = map[e] ? map[e] + 1 : 1; });

		for (var key in map) {
			if (map[key] === 4 && key !== 0) {
				return true;
			}
		}

		return false;
	}

	print(function (n) {

		var answers = [];

		while (n--) answers.push(function () {

			var regiment = [];
			for (var i = 0; i < 4; i++) {
				var newRegiment = readline().split(' ').map(Number);
				regiment.push(newRegiment);
			}

			var moles = [], homes = [];
			for (var i = 0; i < 4; i++) {

				var newMole = {
					x: regiment[i][0],
					y: regiment[i][1]
				};

				var newHome = {
					x: regiment[i][2],
					y: regiment[i][3]
				};

				moles.push(newMole);
				homes.push(newHome);
			}

			var squares = [];
			for (var rotate_1 = 0; rotate_1 < 4; rotate_1++)
				for (var rotate_2 = 0; rotate_2 < 4; rotate_2++)
					for (var rotate_3 = 0; rotate_3 < 4; rotate_3++)
						for (var rotate_4 = 0; rotate_4 < 4; rotate_4++) {
							var mole1 = Rotate(moles[0], homes[0], Math.PI / 2 * rotate_1),
								mole2 = Rotate(moles[1], homes[1], Math.PI / 2 * rotate_2),
								mole3 = Rotate(moles[2], homes[2], Math.PI / 2 * rotate_3),
								mole4 = Rotate(moles[3], homes[3], Math.PI / 2 * rotate_4);

							var differences = isSomeOne(mole1, mole2, mole3, mole4) === false,
								square = isSquare(mole1, mole2, mole3, mole4);
							if (differences && square) {
								squares.push(rotate_1 + rotate_2 + rotate_3 + rotate_4);
							}
						}

			if (squares.length === 0) return -1;
			else if (squares.length === 1) return squares[0];
			else return Math.min.apply(null, squares);

		}());

		return answers.join('\n');

	}(+readline()));

}.call(this));


var n=+readline();
while(n--){
	var s=readline();
	var ans=[];
	var x=[1,2,3,4,6,12].filter(function(k){
		for(var i=0; i<k; i++){
			if(s[i]==='X'){
				var f=true;
				for(var j=i; j<12; j+=k){
					if(s[j]!=='X'){
						f=false;
					}
				}
				if(f){
					return true;
				}
			}
		}
		return false;
	});
	print(x.length===0 ? 0 : x.length+' '+x.map(function(v){return (12/v)+'x'+v;}).reverse().join(' '));
}

;(function () {

	print((function (n) {

		var ret = [];

		while (n--) {
			var p = 0, s = readline(), k = [];

			[1, 2, 3, 4, 6, 12].forEach( function (a) {
				for (var _b = 0, b = 12 / a; _b < b; _b++) {
					for (var j = 0, q = []; j < b; j++) q.push(j === _b ? 'X' : '.');
					q = '(' + q.join('') + '){' + a + '}';
					if ( (new RegExp(q)).test(s) ) {
						k.push(a + 'x' + b);
						p++;
						break;
					}
				}
			});

			if (k.length) {
				k.unshift(p);
				ret.push(k.join(' '));
			} else ret.push('0');
		}

		return ret.join('\n');

	})(+readline()));

}).call(this);

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 caseNum = parseInt(readline());
	for (var caseIndex = 0; caseIndex < caseNum; ++caseIndex) {
		var line = trim(readline());
		var solutions = [];
		for (var rowNum = 1; rowNum <= 12; ++rowNum) {
			if (12%rowNum != 0) {
				continue;
			}
			var colNum = 12/rowNum;
			for (var c = 0; c < colNum; ++c) {
				var okay = true;
				for (var r = 0; okay && r < rowNum; ++r) {
					if (line.charAt(r*colNum+c) == 'O') {
						okay = false;
					}
				}
				if (okay) {
					solutions.push(rowNum+'x'+colNum);
					break;
				}
			}
		}
		solutions.unshift(solutions.length);
		print(solutions.join(' '));
	}
}

main();

var n = +readline();
var width = [12, 6, 4, 3, 2, 1];
for (var i=0; i<n; i++) {
	var s = readline();
	var ans = '';
	var count = 0;
		next: for (var k=0; k<6; k++) {
			next1: for (var j=0; j<width[k]; j++) {

				 for (var z=j; z<12; z += width[k]) {
						if (s[z] != 'X') continue next1;
					}

				ans += ' ' + 12/width[k] + 'x' + width[k];
				count++;
				continue next;
			}
		}
print (count + ans);
}

var t = parseInt(readline()),
		widths = [ 12, 6, 4, 3, 2, 1 ];

	for(var i = 0; i < t; i++)	{
		var row = readline().replace(/o/gi, 0).replace(/x/gi, 1), count = 0, result = [];

		widths.forEach(function(width, i)	{
			var height = 12 / width, s = 0, e = 1, cols = height, rs = [];

			rs = row.split('').map(function(v1, v2, arr)	{
				var returnVal = arr.slice(s, e * height).map(Number);

				s = e * height;
				e++;

				return returnVal;
			}).slice(0, width);

			for(var col = 0; col < cols; col++)	{
				var rsValCheck = 1, flag = true;

				for(var n = 0; n < rs.length; n++)	{
					rsValCheck *= parseInt(rs[n][col]);

					if(!rsValCheck)	{
						flag = false;
						break;
					}
				}

				if(flag)	{
					count++;
					result.push(width);
					break;
				}
			}

		});

		result = result.sort(function(a, b){ return a + b; }).map(function(a) { return a + 'x' + 12 / a });
		print(count + ' ' + result.join(' '));
	}

var n=+readline();
while(n--){
	var s=readline();
	var ans=[];
	var x=[1,2,3,4,6,12].filter(function(k){
		for(var i=0; i<k; i++){
			if(s[i]==='X'){
				var f=true;
				for(var j=i; j<12; j+=k){
					if(s[j]!=='X'){
						f=false;
					}
				}
				if(f){
					return true;
				}
			}
		}
		return false;
	});
	print(x.length===0 ? 0 : x.length+' '+x.map(function(v){return (12/v)+'x'+v;}).join(' '));
}

var t = parseInt(readline()),
		solves = [ 1, 2, 3, 4, 6, 12 ];

	for(var i = 0; i < t; i++)	{
		var row = readline().split(''), count = 0, rs = [],
			json = {
				'12' : 1,
				'6' : 2,
				'4' : 3,
				'3' : 4,
				'2' : 6,
				'1' : 12
			};

		row.forEach(function(c, index)	{
			if(c == 'X')	{
				solves.forEach(function(pos)	{
					if((index + 1) % pos == 0)	json[pos] -= 1;
					if(json[pos] == 0)	{
						count++;

						rs.push(pos);
					}
				});
			}
		});

		rs = rs.sort(function(a, b){ return a + b; }).map(function(a) { return 12 / a + 'x' + a });
		print(count + ' ' + rs.join(' '));
	}

var t = parseInt(readline()),
		solves = [ 1, 2, 3, 4, 6, 12 ];

	for(var i = 0; i < t; i++)	{
		var row = readline().split(''),
			json = {
				'1' : 12,
				'2' : 6,
				'3' : 4,
				'4' : 3,
				'6' : 2,
				'12' : 1
			},
			count = 0, rs = [];

		row.forEach(function(c, index)	{
			if(c == 'X')	{
				solves.forEach(function(pos)	{
					if(!((index + 1) % pos))	json[pos] -= 1;

					if(json[pos] == 0)	{
						count++;

						rs.push(pos + 'x' + 12 / pos);
					}
				});
			}
		});

		print(count + ' ' + rs.join(' '));
	}


const readline = require('readline');
const { setFlagsFromString } = require('v8');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        //do nothing?
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input) + '\n'
    }
    lineCount++
});

function compute(str) {
    var list = str.split(' ')
    var up = false

    for(var i = list.length-2;i>=0;i--){
        if(parseInt(list[i])<parseInt(list[i+1])){
            var up = true
        }
        else if(parseInt(list[i])>parseInt(list[i+1])){
            if(up == true){
                // there's a turn
                return i+1
            }
            else{
                continue
            }
        }
        else{
            continue
        }
    }
    return '0'
}

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++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    if (len === 1) {
      console.log(0);
      continue;
    }
    let i = len - 1;
    let count = 1;

    for (; i >= 1; i--) {
      if (arr[i] > arr[i - 1]) break;
      count++;
    }
    for (; i >= 1; i--) {
      if (arr[i] < arr[i - 1]) break;
      count++;
    }
    console.log(len - count);
  }
}

//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return 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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		var negative = false;
		for(var j = N - 2; j > 0; j--){
			if(list[j] < list[j + 1]){
				negative = true;
			}
			if(list[j - 1] > list[j] && list[j] <= list[j + 1] && negative){
				lastIndex = j;
				break;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   var a1 = [a[0]];
   var fi = [0];
   for (var i = 1; i < n; i++) {
      if (a[i] !== a[i - 1]) {
         a1.push(a[i]);
         fi.push(i);
      }
   }
   var ind = 0;
   var n1 = a1.length;
   for (var i = 1; i < n1 - 1; i++) {
      if (a1[i] < a1[i + 1] && a1[i] < a1[i - 1]) {
         ind = fi[i];
      }
   }
   write(ind);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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

//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return 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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		for(var j = N - 2; j > 0; j--){
			if(list[j - 1] > list[j] && list[j] < list[j + 1]){
				lastIndex = j;
				break;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return 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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		for(var j = N - 2; j > 0; j--){
			if(list[j - 1] > list[j] && list[j] <= list[j + 1]){
				lastIndex = j;
				break;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

//↓見なくていいよ！ここから--------------------------------------------------
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 = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return 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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		var max = 0;
		for(var j = N - 2; j > 0; j--){
			if(list[j - 1] > list[j] && list[j] < list[j + 1]){
				lastIndex = j;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

const readline = require('readline');
const { setFlagsFromString } = require('v8');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        //do nothing?
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input) + '\n'
    }
    lineCount++
});

function compute(str) {
    var list = str.split(' ')
    var up = false

    for(var i = list.length-2;i>=0;i--){
        if(parseInt(list[i])<parseInt(list[i+1])){
            var up = true
        }
        else{
            if(up == true){
                // there's a turn
                return i+1
            }
            else{
                continue
            }
        }
    }
    return '0'
}

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   var ind = 0;
   for (var i = 1; i < n - 1; i++) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
      }
   }
   write(ind);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   if (n < 3) {
      write(0);
      return;
   }
   var ind = 0;
   for (var i = n - 2; i > 0; i--) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
         break;
      }
   }
   write(ind);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   if (n < 3) {
      write(0);
      return;
   }
   var ind = 0;
   for (var i = n - 2; i > 0; i--) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
         break;
      }
   }
   write(i);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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

function solve() {
   var n = Number(read());
   if (n === 1) {
      write(-1);
      return;
   }
   var a = readArray(Number);
   var a1 = [a[0]];
   var fi = [0];
   for (var i = 1; i < n; i++) {
      if (a[i] !== a[i - 1]) {
         a1.push(a[i]);
         fi.push(i);
      }
   }
   var ind = 0;
   var n1 = a1.length;
   for (var i = 1; i < n1 - 1; i++) {
      if (a1[i] < a1[i + 1] && a1[i] < a1[i - 1]) {
         ind = fi[i];
      }
   }
   write(ind);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   var ind = 0;
   for (var i = n - 2; i > 0; i--) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
         break;
      }
   }
   write(i);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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