A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
/* var arr = readLine().split(" ").map((x) => {return parseInt(x)});
var test = readLine();
while(test--)
{

}
*/
function main() {
    var test = readLine();

    while(test--)
    {
        var coordinates = readLine().split(" ").map((x) => {return parseInt(x)});
        var w = coordinates[0];
        var h = coordinates[1];
        var x_when_y_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var x_when_y_h = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_w = readLine().split(" ").map((x) => {return parseInt(x)});
        var length_of_x_when_y_zero = x_when_y_zero[0] - 1;
        var length_of_x_when_y_h = x_when_y_h[0] - 1;
        var length_of_y_when_zero = y_when_x_zero[0] - 1;
        var length_of_y_when_w = y_when_x_w[0] - 1;
        x_when_y_zero.shift();
        x_when_y_h.shift();
        y_when_x_zero.shift();
        y_when_x_w.shift();
        x_when_y_zero.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        x_when_y_h.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        y_when_x_zero.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        y_when_x_w.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        var res = [
            x_when_y_zero[length_of_x_when_y_zero]-x_when_y_zero[0],
            x_when_y_h[length_of_x_when_y_h]-x_when_y_h[0],
            y_when_x_zero[length_of_y_when_zero]-y_when_x_zero[0],
            y_when_x_w[length_of_y_when_w]-y_when_x_w[0]
        ];

        res[0] = res[0]*h;
        res[1] = res[1]*h;
        res[2] = res[2]*w;
        res[3] = res[3]*w;
        res.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });
        res.reverse();
        console.log(res[0]);
    }
    return 0;
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
/* var arr = readLine().split(" ").map((x) => {return parseInt(x)});
var test = readLine();
while(test--)
{

}
*/
function main() {
    var test = readLine();

    while(test--)
    {
        var coordinates = readLine().split(" ").map((x) => {return parseInt(x)});
        var w = BigInt(coordinates[0]);
        var h = BigInt(coordinates[1]);
        var x_when_y_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var x_when_y_h = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_w = readLine().split(" ").map((x) => {return parseInt(x)});
        var length_of_x_when_y_zero = BigInt(x_when_y_zero[0] - 1);
        var length_of_x_when_y_h = BigInt(x_when_y_h[0] - 1);
        var length_of_y_when_zero = BigInt(y_when_x_zero[0] - 1);
        var length_of_y_when_w = BigInt(y_when_x_w[0] - 1);
        x_when_y_zero.shift();
        x_when_y_h.shift();
        y_when_x_zero.shift();
        y_when_x_w.shift();
        x_when_y_zero.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        x_when_y_h.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        y_when_x_zero.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        y_when_x_w.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        var res = [
            BigInt(x_when_y_zero[length_of_x_when_y_zero]-x_when_y_zero[0]),
            BigInt(x_when_y_h[length_of_x_when_y_h]-x_when_y_h[0]),
            BigInt(y_when_x_zero[length_of_y_when_zero]-y_when_x_zero[0]),
            BigInt(y_when_x_w[length_of_y_when_w]-y_when_x_w[0])
        ];

        res[0] = res[0]*h;
        res[1] = res[1]*h;
        res[2] = res[2]*w;
        res[3] = res[3]*w;
        res.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });
        res.reverse();
        console.log(String(res[0]));
    }
    return 0;
}

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

let inputString = '';

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

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

    main(inputString);
});

function log(message){
    if(process.env.NODE_ENV === "debug"){
        console.log(message);
    }
}

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);
    for(let i = 0; i < fileContents.length; i+=5){
        triangleScenarioHigh(fileContents[i],fileContents[i+1],fileContents[i+2],fileContents[i+3],fileContents[i+4])
    }
}
function triangleScenarioHigh(corner,horizontal0,horizontalY,vertical0,verticalX){
    // console.log("corner,horizontal0,horizontalY,vertical0,verticalX")
    // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)

    triangleScenarioLow(corner.split(" "),
        horizontal0.split(" ").slice(1),
        horizontalY.split(" ").slice(1),
        vertical0.split(" ").slice(1),
        verticalX.split(" ").slice(1))
}

function triangleScenarioLow(corner,horizontal0,horizontalY,vertical0,verticalX){
    // console.log("corner,horizontal0,horizontalY,vertical0,verticalX")
    // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)
    const YCorner = parseInt(corner[1]) //8
    const XCorner = parseInt(corner[0]) //5
    const points = [
        [[parseInt(horizontal0[0]),0],[parseInt(horizontal0[horizontal0.length-1]),0]],
        [[parseInt(horizontalY[0]),YCorner],[parseInt(horizontalY[horizontalY.length-1]),YCorner]],
        [[0,parseInt(vertical0[0])],[0,parseInt(vertical0[vertical0.length-1])]],
        [[XCorner,parseInt(verticalX[0])],[XCorner,parseInt(verticalX[verticalX.length-1])]],
    ]

    // console.log("points",points) //xxx

    let biggestArea = 0

    for(i = 0; i < points.length; i++){
        for(i2 = 0; i2 < points.length; i2++){
                if(i !== i2){
                    let length1 = Math.sqrt(Math.pow(points[i][0][0] -  points[i2][0][0],2) + Math.pow(points[i][0][1] -  points[i2][0][1],2))
                    let length2 = Math.sqrt(Math.pow(points[i][1][0] -  points[i2][0][0],2) + Math.pow(points[i][1][1] -  points[i2][0][1],2))
                    let length3 = Math.sqrt(Math.pow(points[i][0][0] -  points[i][1][0],2) + Math.pow(points[i][0][1] -  points[i][1][1],2))
                    biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);
                     length1 = Math.sqrt(Math.pow(points[i][0][0] -  points[i2][1][0],2) + Math.pow(points[i][0][1] -  points[i2][1][1],2))
                     length2 = Math.sqrt(Math.pow(points[i][1][0] -  points[i2][1][0],2) + Math.pow(points[i][1][1] -  points[i2][1][1],2))
                     length3 = Math.sqrt(Math.pow(points[i][0][0] -  points[i][1][0],2) + Math.pow(points[i][0][1] -  points[i][1][1],2))
                    biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);

                }
        }
    }

    console.log(Math.round(biggestArea));

}

function findArea( a,  b,  c)
{
    if (a < 0 || b < 0 || c < 0 ||
        (a + b <= c) || a + c <= b ||
        b + c <= a)
    {
        return -1;
    }
    let s = (a + b + c) / 2;
    return Math.sqrt(s * (s - a) *
        (s - b) * (s - c));
}

const getMaximum = arr=>arr[arr.length-1] - arr[1];
const solve = (w,h,arr)=>{
     let t = h,max = 0;
     for(let i=1;i<=4;i++){
          if(i>2) t = w;
          let v = getMaximum(arr[i-1])*t;
          if(v>=max) max = v;
     }
     console.log(max);
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [w,h] = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr= [];
       for(let i=0;i<4;i++)
          arr.push(readline().trim().split(" ").map(cur=>parseInt(cur)));
     solve(w,h,arr);
  }
}
main();

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--) {
		const [w, h] = rna();

		function go (height) {
			const ar = rna().slice(1);
			ar.sort((x, y) => x - y);
			ans = Math.max(ans, height * (ar[ar.length - 1] - ar[0]));
		}

		let ans = 0;
		go(h);
		go(h);
		go(w);
		go(w);

		console.log(ans);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

// function foo(x) {
//   process.stdout.write("hello: ");   // without auto '\n' (newline)
//   console.log(x);  // with auto '\n' (newline)
// }

const print = x => {
  process.stdout.write(x.toString());
  process.stdout.write("\n");
};

function main() {
  const n = readline();

  for (let test = 0; test < n; test += 1) {
    const [w, h] = readline().split(' ');

    const getMaxDistanceBetween = () => {
      const arr = readline().split(' ');
      let mn = 1000 * 1000 + 3;
      let mx = 0;
      for (let i = 1; i < arr.length; i++) {
        mn = Math.min(mn, arr[i]);
        mx = Math.max(mx, arr[i]);
      }
      return mx - mn;
    }

    const down = getMaxDistanceBetween();
    const up = getMaxDistanceBetween();
    const left = getMaxDistanceBetween();
    const right = getMaxDistanceBetween();

    const ans = Math.max(
      down * h,
      up * h,
      left * w,
      right * w,
    )

    print(ans);
  }

}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let [t] = readline().split(' ').map(num => parseInt(num));
    for (let i = 0; i < t; i++) {
        let [w, h] = readline().split(' ').map(num => parseInt(num));
        let x1 = readline().split(' ').map(num => parseInt(num));
        let x2 = readline().split(' ').map(num => parseInt(num));
        let y1 = readline().split(' ').map(num => parseInt(num));
        let y2 = readline().split(' ').map(num => parseInt(num));
        let t1 = (x1[x1.length - 1] - x1[1]) * h;
        let t2 = (x2[x2.length - 1] - x2[1]) * h;
        let t3 = (y1[y1.length - 1] - y1[1]) * w;
        let t4 = (y2[y2.length - 1] - y2[1]) * w;
        console.log(Math.max(t1, t2, t3, t4));
    }
}

function S(a, b, c) {
  return Math.abs(
    (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
  );
}

function solve(points) {
  var answers = [0, 0, 0, 0];
  for (var i = 0; i < 4; i++) {
    a = points[i][0];
    b = points[i][points[i].length - 1];

    for (var j = 0; j < 4; j++) {
      if (i === j) continue;

      for (var c of points[j]) {
        answers[i] = Math.max(answers[i], S(a, b, c));
      }
    }
  }

  return Math.max.apply(null, answers);
}

var _i = 0;
var _input = `3
5 8
2 1 2
3 2 3 4
3 1 4 6
2 4 5
10 7
2 3 9
2 1 7
3 1 3 4
3 4 5 6
11 5
3 1 6 8
3 3 6 8
3 1 3 4
2 2 4
`.split("\n");

t = Number(readline());
points = [[], [], [], []];

for (var i = 0; i < t; i++) {
  var wh = readline().split(" ").map(Number);
  var w = wh[0];
  var h = wh[1];
  var snd_coords = [0, h, 0, w];

  points.forEach(function (p, i) {
    points[i] = readline()
      .split(" ")
      .slice(1)
      .map(Number)
      .map(function (x) {
        return i < 2 ? [x, snd_coords[i]] : [snd_coords[i], x];
      });
  });

  // console.log(points);

  print(solve(points));
}

// function readline() {
//   return _input[_i++];
// }

// function print(val) {
//   console.log(val);
// }

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
/* var arr = readLine().split(" ").map((x) => {return parseInt(x)});
var test = readLine();
while(test--)
{

}
*/
function main() {
    var test = readLine();

    while(test--)
    {
        var coordinates = readLine().split(" ").map((x) => {return parseInt(x)});
        var w = BigInt(coordinates[0]);
        var h = BigInt(coordinates[1]);
        var x_when_y_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var x_when_y_h = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_w = readLine().split(" ").map((x) => {return parseInt(x)});
        var length_of_x_when_y_zero = BigInt(x_when_y_zero[0] - 1);
        var length_of_x_when_y_h = BigInt(x_when_y_h[0] - 1);
        var length_of_y_when_zero = BigInt(y_when_x_zero[0] - 1);
        var length_of_y_when_w = BigInt(y_when_x_w[0] - 1);
        x_when_y_zero.shift();
        x_when_y_h.shift();
        y_when_x_zero.shift();
        y_when_x_w.shift();
        x_when_y_zero.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        x_when_y_h.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        y_when_x_zero.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        y_when_x_w.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });;
        var res = [
            BigInt(x_when_y_zero[length_of_x_when_y_zero]-x_when_y_zero[0]),
            BigInt(x_when_y_h[length_of_x_when_y_h]-x_when_y_h[0]),
            BigInt(y_when_x_zero[length_of_y_when_zero]-y_when_x_zero[0]),
            BigInt(y_when_x_w[length_of_y_when_w]-y_when_x_w[0])
        ];
        console.log(String(res));
        res[0] = res[0]*h;
        res[1] = res[1]*h;
        res[2] = res[2]*w;
        res[3] = res[3]*w;
        res.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });
        res.reverse();
        console.log(String(res[0]));
    }
    return 0;
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
/* var arr = readLine().split(" ").map((x) => {return parseInt(x)});
var test = readLine();
while(test--)
{

}
*/
function main() {
    var test = readLine();

    while(test--)
    {
        var coordinates = readLine().split(" ").map((x) => {return parseInt(x)});
        var w = BigInt(coordinates[0]);
        var h = BigInt(coordinates[1]);
        var x_when_y_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var x_when_y_h = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_w = readLine().split(" ").map((x) => {return parseInt(x)});
        var length_of_x_when_y_zero = x_when_y_zero[0];
        var length_of_x_when_y_h = x_when_y_h[0];
        var length_of_y_when_zero = y_when_x_zero[0];
        var length_of_y_when_w = y_when_x_w[0];
        x_when_y_zero.shift();
        x_when_y_h.shift();
        y_when_x_zero.shift();
        y_when_x_w.shift();
        x_when_y_zero.sort();
        x_when_y_h.sort();
        y_when_x_zero.sort();
        y_when_x_w.sort();
        var res = [
            BigInt(x_when_y_zero[length_of_x_when_y_zero-1]-x_when_y_zero[0]),
            BigInt(x_when_y_h[length_of_x_when_y_h-1]-x_when_y_h[0]),
            BigInt(y_when_x_zero[length_of_y_when_zero-1]-y_when_x_zero[0]),
            BigInt(y_when_x_w[length_of_y_when_w-1]-y_when_x_w[0])
        ];
        res[0] = res[0]*h;
        res[1] = res[1]*h;
        res[2] = res[2]*w;
        res[3] = res[3]*w;
        res.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });
        res.reverse();
        console.log(String(res[0]));
    }
    return 0;
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
/* var arr = readLine().split(" ").map((x) => {return parseInt(x)});
var test = readLine();
while(test--)
{

}
*/
function main() {
    var test = readLine();

    while(test--)
    {
        var coordinates = readLine().split(" ").map((x) => {return parseInt(x)});
        var w = coordinates[0];
        var h = coordinates[1];
        var x_when_y_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var x_when_y_h = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_w = readLine().split(" ").map((x) => {return parseInt(x)});
        var length_of_x_when_y_zero = x_when_y_zero[0];
        var length_of_x_when_y_h = x_when_y_h[0];
        var length_of_y_when_zero = y_when_x_zero[0];
        var length_of_y_when_w = y_when_x_w[0];
        x_when_y_zero.shift();
        x_when_y_h.shift();
        y_when_x_zero.shift();
        y_when_x_w.shift();
        x_when_y_zero.sort();
        x_when_y_h.sort();
        y_when_x_zero.sort();
        y_when_x_w.sort();
        var res = [
            x_when_y_zero[length_of_x_when_y_zero-1]-x_when_y_zero[0],
            x_when_y_h[length_of_x_when_y_h-1]-x_when_y_h[0],
            y_when_x_zero[length_of_y_when_zero-1]-y_when_x_zero[0],
            y_when_x_w[length_of_y_when_w-1]-y_when_x_w[0]
        ];
        res[0] = res[0]*h;
        res[1] = res[1]*h;
        res[2] = res[2]*w;
        res[3] = res[3]*w;
        res.sort((a ,b) => {
            if(a > b) {
                return 1;
            } else if (a < b){
                return -1;
            } else {
                return 0;
            }
        });
        res.reverse();
        console.log(res[0]);
    }
    return 0;
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
/* var arr = readLine().split(" ").map((x) => {return parseInt(x)});
var test = readLine();
while(test--)
{

}
*/
function main() {
    var test = readLine();

    while(test--)
    {
        var coordinates = readLine().split(" ").map((x) => {return parseInt(x)});
        var w = coordinates[0];
        var h = coordinates[1];
        var x_when_y_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var x_when_y_h = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_zero = readLine().split(" ").map((x) => {return parseInt(x)});
        var y_when_x_w = readLine().split(" ").map((x) => {return parseInt(x)});
        var length_of_x_when_y_zero = x_when_y_zero[0];
        var length_of_x_when_y_h = x_when_y_h[0];
        var length_of_y_when_zero = y_when_x_zero[0];
        var length_of_y_when_w = y_when_x_w[0];
        x_when_y_zero.shift();
        x_when_y_h.shift();
        y_when_x_zero.shift();
        y_when_x_w.shift();
        x_when_y_zero.sort();
        x_when_y_h.sort();
        y_when_x_zero.sort();
        y_when_x_w.sort();
        var res = [
            x_when_y_zero[length_of_x_when_y_zero-1]-x_when_y_zero[0],
            x_when_y_h[length_of_x_when_y_h-1]-x_when_y_h[0],
            y_when_x_zero[length_of_y_when_zero-1]-y_when_x_zero[0],
            y_when_x_w[length_of_y_when_w-1]-y_when_x_w[0]
        ];
        res[0] = res[0]*h;
        res[1] = res[1]*h;
        res[2] = res[2]*w;
        res[3] = res[3]*w;
        res.sort((a, b) => a-b);
        res.reverse();
        console.log(res[0]);
    }
    return 0;
}

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

let inputString = '';

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

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

    main(inputString);
});

function log(message){
    if(process.env.NODE_ENV === "debug"){
        console.log(message);
    }
}

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);
    for(let i = 0; i < fileContents.length; i+=5){
        triangleScenarioHigh(fileContents[i],fileContents[i+1],fileContents[i+2],fileContents[i+3],fileContents[i+4])
    }
}
function triangleScenarioHigh(corner,horizontal0,horizontalY,vertical0,verticalX){
    // console.log("corner,horizontal0,horizontalY,vertical0,verticalX")
    // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)

    triangleScenarioLow(corner.split(" "),
        horizontal0.split(" ").slice(1),
        horizontalY.split(" ").slice(1),
        vertical0.split(" ").slice(1),
        verticalX.split(" ").slice(1))
}

function triangleScenarioLow(corner,horizontal0,horizontalY,vertical0,verticalX){
    // console.log("corner,horizontal0,horizontalY,vertical0,verticalX")
    // console.log(corner,horizontal0,horizontalY,vertical0,verticalX)
    const YCorner = parseInt(corner[1]) //8
    const XCorner = parseInt(corner[0]) //5
    const points = [
        [[parseInt(horizontal0[0]),0],[parseInt(horizontal0[horizontal0.length-1]),0]],
        [[parseInt(horizontalY[0]),YCorner],[parseInt(horizontalY[horizontal0.length-1]),YCorner]],
        [[0,parseInt(vertical0[0])],[0,parseInt(vertical0[vertical0.length-1])]],
        [[XCorner,parseInt(verticalX[0])],[XCorner,parseInt(verticalX[verticalX.length-1])]],
    ]

    // console.log("points",points)

    let biggestArea = 0

    for(i = 0; i < points.length; i++){
        for(i2 = 0; i2 < points.length; i2++){
                if(i !== i2){
                    let length1 = Math.sqrt(Math.pow(points[i][0][0] -  points[i2][0][0],2) + Math.pow(points[i][0][1] -  points[i2][0][1],2))
                    let length2 = Math.sqrt(Math.pow(points[i][1][0] -  points[i2][0][0],2) + Math.pow(points[i][1][1] -  points[i2][0][1],2))
                    let length3 = Math.sqrt(Math.pow(points[i][0][0] -  points[i][1][0],2) + Math.pow(points[i][0][1] -  points[i][1][1],2))
                    biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);
                     length1 = Math.sqrt(Math.pow(points[i][0][0] -  points[i2][1][0],2) + Math.pow(points[i][0][1] -  points[i2][1][1],2))
                     length2 = Math.sqrt(Math.pow(points[i][1][0] -  points[i2][1][0],2) + Math.pow(points[i][1][1] -  points[i2][1][1],2))
                     length3 = Math.sqrt(Math.pow(points[i][0][0] -  points[i][1][0],2) + Math.pow(points[i][0][1] -  points[i][1][1],2))
                    biggestArea = Math.max(biggestArea,findArea(length1,length2,length3)*2);

                }
        }
    }

    console.log(Math.round(biggestArea));

}

function findArea( a,  b,  c)
{
    if (a < 0 || b < 0 || c < 0 ||
        (a + b <= c) || a + c <= b ||
        b + c <= a)
    {
        return -1;
    }
    let s = (a + b + c) / 2;
    return Math.sqrt(s * (s - a) *
        (s - b) * (s - c));
}


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;
	const [n, m] = inputReader.readNumberArray();
	const arr = inputReader.readNumberArray();
	let current = 1;
	let time = 0;
	for (let i = 0; i < arr.length; i++) {
		if(current<=arr[i]){
			time+=Math.abs(current-arr[i]);
			current=arr[i];
		}
		else{
			time+=Math.abs(current-n) + Math.abs(1-arr[i])+1;
			current=arr[i];
		}
	}
	console.log(time);

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumberArray(){
		return _inputLines[_lineNumber++].split(' ').map(val => Number(val));
	}

	return {
		readNumberArray,
	}
}

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 [totalHouses, tasksLen] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const tasks = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let count = tasks[0] - 1;

  for (let i = 0; i < tasksLen - 1; i++) {
    const diff = tasks[i + 1] - tasks[i];
    if (diff >= 0) {
      count += diff;
    } else {
      const steps = totalHouses - tasks[i] + tasks[i + 1];
      count += steps;
    }
  }
  console.log(count);
}

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  let [n, m]  = input[0].split(' ').map(x => parseInt(x));
  const deway = input[1].split(' ').map(x => parseInt(x));
  let stay = 1;
  let answer = 0;

  for (let i = 0; i < deway.length; i += 1) {
    if (stay > deway[i]) {
      answer += (n - stay + deway[i]);
    } else {
      answer += deway[i]-stay;
    }
    stay = deway[i];
  }

  console.log(answer);
});

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

const input = [];

function splitAndParseInt(line) {
  return line.split(" ").map((x) => parseInt(x));
}

readLine.on("line", (line) => input.push(line));
readLine.on("close", () => {
  let [n, m] = splitAndParseInt(input[0]);
  const nums = splitAndParseInt(input[1]);

  let answer = 0,
    pos = 1;
  for (const num of nums) {
    if (pos <= num) {
      answer += num - pos;
    } else {
      answer += num + (n - pos);
    }
    pos = num;
  }
  console.log(answer);
});

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 [n, m] = readLine()
		.split(' ')
		.map(x => parseInt(x));

	let tasks = readLine()
		.split(' ')
		.map(x => parseInt(x));

	let current = 1;
	let total = 0;

	tasks.forEach(task => {
		if (task >= current) {
			total += task - current;
		} else {
			total += n - current + task;
		}
		current = task;
	});

	console.log(total);
}

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split(/[\n\r]/).filter(data => data.length > 0);

for (let i = 0; i < txt.length; i += 2) {
    let info = txt[i].split(" ")[0] * 1;
    doit(info, txt[i + 1].split(/[ ]/).filter(data => data.length > 0).map(dta => dta * 1));
}

function doit(n, tab) {
    let moves = tab[0] - 1;
    for (let i = 0; i < tab.length - 1; i++) {
        if (tab[i + 1] >= tab[i]) {
            moves += tab[i + 1] - tab[i];
        } else {
            moves += tab[i + 1] + (n - tab[i]);
        }

    }
    console.log(moves);
}

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

var ans=n;
for(var i=1; i<m; i++){
	if(a[i]<a[i-1]){
		ans+=n;
	}
}
print(ans-n+a[a.length-1]-1);

var input = readline().split(" "), n = +input[0], m = +input[1], a = readline().split(" "), b = 1, time = 0;

for(j = 0; j < m; j++){
	if(b < +a[j]){
		time += +a[j] - b;
		b = +a[j];
	}
	else if(b > +a[j]){
		time += n - b + +a[j];
		b = +a[j];
	}
}

write(time);

var meta = readline().split(' ').map((as)=> parseInt(as))
var time = 0, res = 0, start = 1
readline().split(' ').map((c)=> parseInt(c)).forEach((val)=>{
	res = val - start;
	if (res < 0){
		time += (meta[0] - start) + val
	}
	else{
		time += val - start
	}
	start = val
})
print(time)

;(function () {

	var s = readline().split(' ');
	var n = +s[0];
	var m = +s[1];
	var a = readline().split(' ').map(function (i) { return +i; });
	var ans = n;

	for(var i = 1; i < m; i++)
		if (a[i] < a[i-1])
			ans += n;

	print(ans - n + a[a.length - 1] - 1);

}).call(this);

var s = readline().split(" ");
var n = Number(s[0]), m = Number(s[1]);

s = readline().split(" ").map(Number);
var t = s[0] - 1;
for(var i=1; i<m; i++) {
    if (s[i] < s[i-1]) {
        t+= n - (s[i-1] - s[i])
    }
    else {
        t+= s[i] - s[i-1];
    }
}
print(t);

var nm=readline().split(' ').map(function(x){return parseInt(x);});
var a=readline().split(' ').map(function(x){return parseInt(x);});
var ans=0;
function abs( x )
{
    if(x<0)x*=-1;
    return x;
}
a.unshift(1);
for(var i=1;i<=nm[1];i++)
{
    if(a[i-1]>a[i]){ans+=abs(a[i-1]-nm[0]); ans++; a[i-1]=1;}
    ans+=abs(a[i]-a[i-1]);
}
print(ans);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;
for(var i=0;i<m.length;i++)
    m[i]=parseInt(m[i]);

var cur=1,t=0,ts='';
for(var i=0;i<m.length;i++)
{
    if(m[i]<cur) t+=(n-cur)+m[i];
    if(m[i]>=cur) t+=m[i]-cur;
    cur=m[i];

//ts+=' '+t;
}
print(t);

'use strict'

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

String.prototype.getNumber = function() {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  })[0];
}

let n = readline().getNumber(),
    array = readline().getNumArray(),
    time = 0;

array.unshift(1);

let calcTime = (time, destinationBuilding, currentBuilding, totalAmountOfBuildings) => {
  if(destinationBuilding < currentBuilding) {
    time+=totalAmountOfBuildings - currentBuilding + 1;
    time+=destinationBuilding - 1;
  } else if (destinationBuilding > currentBuilding) {
    time+=destinationBuilding - currentBuilding;
  }

  return time;
}

for (let i = 0; i < array.length - 1; i++) {
  time = calcTime(time, array[i+1], array[i], n);
}

write(time)

var str = readline().split(" ");
var n = +str[0]; var m = +str[1];
var house = readline().split(" ");
var temp = 1;   var res = 0;
	for(var i=0; i<m; i++){

		if (temp<house[i])    //1 3
			res += +house[i]-temp; // 2
		else if (temp>house[i]) // 			3 2
			res+= n-temp+Number(house[i]);

			 temp = +house[i]; // 3
	}
print(res);

var n = readline().split(" ").map(function(x) { return parseInt(x); })[0];
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var diff = a[0] - 1;
for (var i = 0; i < a.length - 1; i++) {
	diff += ((a[i+1] >= a[i]) ? (a[i+1] - a[i]) : (n - a[i] + a[i + 1]));
}
print (diff);

var ringRoad = function(n, arr)
        {
            var counter = arr[0] - 1;
            for (var i = 1; i <= arr.length - 1; i++)
            {
                if (arr[i] >= arr[i - 1])
                    {
                         counter += arr[i] - arr[i - 1];
                         continue;
                    }
                else {
					//if (arr[i - 1] !== n)
                    counter += n - arr[i - 1] + arr[i];
					//else counter += 1;
                }
            }
			return counter;
        }
    var toNumArr = function(str)
    {
        str = str.split(' ');
        for (var i = 0 ; i <= str.length - 1; i++)
        {
            str[i] = +str[i];
        }
        return str;
    }
    var num = toNumArr(readline());
    var input = toNumArr(readline());
    print(ringRoad(num[0], input));

var ringRoad = function(n, arr)
        {
            var counter = arr[0] - 1;
            for (var i = 1; i <= arr.length - 1; i++)
            {
                if (arr[i] > arr[i - 1])
                    {
                         counter += arr[i] - arr[i - 1];
                         continue;
                    }
                else if (arr[i] < arr[i - 1]) {
					//if (arr[i - 1] !== n)
                    counter += n - arr[i - 1] + arr[i];
					//else counter += 1;
                }
            }
			return counter;
        }
    var toNumArr = function(str)
    {
        str = str.split(' ');
        for (var i = 0 ; i <= str.length - 1; i++)
        {
            str[i] = +str[i];
        }
        return str;
    }
    var num = toNumArr(readline());
    var input = toNumArr(readline());
    print(ringRoad(num[0], input));

var inp = readline().split(' ');
var a = readline().split(' ');

for(var i=0; i<inp.length; i++) {
    inp[i] = parseInt(inp[i], 10);
}
var n = inp[0], m = inp[1];

for(var i=0; i<a.length; i++) {
    a[i] = parseInt(a[i], 10);
}

var path = 0;

for(var i=0; i<a.length; i++) {
    if(i === 0) path += a[i] - 1;
    else {
        if(a[i] > a[i-1]) path += a[i] - a[i-1];
        else if(a[i] < a[i-1]) {
            path += n - a[i-1];
            path += 1;
            path += a[i] - 1;
        }
    }
}

print(path);

var nums = readNums();

var n = nums[0];
var m = nums[1];

var things = readNums();

var k = 0;

for (var i = 0; i<m ;i++) {

    if (i == 0) {
        k += things[i]-1;
    }else{
        if (things[i] < things[i-1]) {
            k += (things[i]+(n-things[i-1]));
        }else{
            k += (things[i]-things[i-1]);
        }
    }
}

print(k);

function readNums() {
    return readline().split(' ').map(function(v) {
        return v - 0;
    })
}

a =readline().split(' ').map(Number);
b =readline().split(' ').map(Number);
d = b[0]-1;
for (i=1;i<b.length;i++){
	k = b[i]-b[i-1];
	if (k<0){
		d += a[0]+k;
	}
	else {
		d += k
	}
}
print(d);

var input = readline().split(' ');
var n = +input[0];
var m = +input[1];
var arr = readline().split(' ');

var cp = 1;
var result = 0;

for (var i = 0; i < m; ++i) {
    var np = +arr[i];
    result += (np - cp + n) % n;
    cp = np;
}

write(result);

X=readline().split(' ').map(Number)
n=X[0], m=X[1]
A=readline().split(' ').map(Number)
r=A.reduce((a,c) => {
	if (c >= a.now) {
		a.sum += c - a.now;
	} else {
		a.sum += n - a.now + c;
	}
	a.now = c;
	return a;
}, { now: 1, sum: 0 });
print(r.sum)

X=readline().split(' ').map(Number)
n=X[0], m=X[1]
A=readline().split(' ').map(Number)
print(A.reduce((a,c) => ({
	sum: a.sum + (c >= a.now ? (c - a.now) : (n - a.now + c)),
	now: c,
}), { now: 1, sum: 0 }).sum);

var a =readline().split(' ').map(Number);
var b =readline().split(' ').map(Number);
d = b[0]-1;
for(var i = 1;i<b.length;i++){
    var k = b[i]-b[i-1];
    if(k<0){
        d+= k +a[0];
    }
    else d+=k;
}
print(d);

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split(/[\n\r]/).filter(data => data.length > 0);

for (let i = 0; i < txt.length; i += 2) {
    let info = txt[i].split(" ")[0] * 1;
    doit(info, txt[i + 1].split(/[ ]/).filter(data => data.length > 0).map(dta => dta * 1));
}

function doit(n, tab) {
  let moves=tab[0]-1;
  for (let i = 0; i < tab.length-1; i++) {
      if(tab[i+1]>=tab[i]){
          moves+=tab[i+1]-tab[i];
      }else{
          moves+=tab[i+1]-1;
          moves+=(n%tab[i])+1;
      }

  }
  console.log(moves);

}

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split(/[\n\r]/).filter(data => data.length > 0);

for (let i = 0; i < txt.length; i += 2) {
    let info = txt[i].split(" ")[0] * 1;
    doit(info, txt[i + 1].split(/[ ]/).filter(data => data.length > 0).map(dta => dta * 1));
}

function doit(n, tab) {
    let moves = tab[0] - 1;
    for (let i = 0; i < tab.length - 1; i++) {
        if (tab[i + 1] >= tab[i]) {
            moves += tab[i + 1] - tab[i];
        } else {
            moves += tab[i + 1] + (n % tab[i]);
        }

    }
    console.log(moves);

}

var input = readline().split(" "), n = +input[0], m = +input[1], a = readline().split(" "), i = 1, j = 0, time = 0;

for( ; j != m ; i++, time++){
	write(i,j,time + "\n");
	if(i == +a[j]){
		j++;
		for( ; ; ){
			if(i == +a[j]){
				j++;
			}
			else{
				break;
			}
		}
	}
	if(i == n){
		i = 0;
	}
}

write(time-1);

var meta = readline().split(' ').map((as)=> parseInt(as))
var time = 0, res = 0, start = 1
readline().split(' ').map((c)=> parseInt(c)).forEach((val)=>{
	res = val - start;
	if (res < 0){
		time += (meta[0] - val) + Math.abs(res)
	}
	else{
		time += val - start
	}
	start = val
})
print(time)

;(function () {

	var x = 0,

		n = +readline().split(' ')[0],

		s = readline()
			.split(' ')
			.map(function (i) {return +i;})
			.filter(function (e, i, a) { return (i == a.length - 1) || a[i] != a[i+1]; }),

		step = (function (n) {
			var i = 1;
			return function () {
				x++;
				i = n == i ? 1 : i+1;
				return i;
			}
		})(n);

	if (s[0] == 1) s.slice(0,1);

	for (var i = 0; i < s.length; i++)
		while (step() != s[i]);

	print(x);

}).call(this);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    if(m[i]<=cur) t+=parseInt((n-cur)+m[i]);
    if(m[i]>cur) t+=parseInt(m[i]-cur);
    cur=m[i];

}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    //for(var j=i+1;m[i]==m[j];j++) i=j;
    if(m[i]<+cur) t+=(n-cur)+m[i];
    if(m[i]>cur) t+=(m[i]-cur);
    cur=i;
}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    //for(var j=i+1;m[i]==m[j];j++) i=j;
    if(m[i]<=cur) t+=(n-cur)+m[i];
    if(m[i]>cur) t+=(m[i]-cur);
    cur=m[i];

print(t);
}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;
for(var i=0;i<m.length;i++)
    m[i]=parseInt(m[i]);

var cur=1,t=0,ts='';
for(var i=0;i<m.length;i++)
{
    if(m[i]<cur) t+=(n-cur)+m[i];
    if(m[i]>=cur) t+=m[i]-cur;
    cur=m[i];

//ts+=' '+t;
}
print(ts);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    //for(var j=i+1;m[i]==m[j];j++) i=j;
    if(m[i]<=cur) t+=(n-cur)+m[i];
    if(m[i]>cur) t+=(m[i]-cur);
    cur=m[i];
}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    for(var j=i+1;m[i]==m[j];j++) i=j;
    if(m[i]<cur) t+=(n-cur)+m[i];
    if(m[i]>=cur) t+=(m[i]-cur);
    cur=i;
}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;
for(var i=0;i<m.length;i++)
    m[i]=parseInt(m[i]);

var cur=1,t=0,ts='';
for(var i=0;i<m.length;i++)
{
    if(m[i]<=cur) t+=(n-cur)+m[i];
    if(m[i]>cur) t+=m[i]-cur;
    cur=m[i];

ts+=' '+t;
}
print(ts);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;
for(var i=0;i<m.length;i++)
m[i]=parseInt(m[i]);

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    if(m[i]<=cur) t+=parseInt((n-cur)+m[i]);
    if(m[i]>cur) t+=parseInt(m[i]-cur);
    cur=m[i];
}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    //for(var j=i+1;m[i]==m[j];j++) i=j;
    if(m[i]<=cur) t+=(n-cur)+m[i];
    if(m[i]>cur) t+=(m[i]-cur);
    cur=i;
}
print(t);

var l1=readline().split(' ');
var l2=readline().split(' ');
var n=parseInt(l1[0]);
var m=l2;
for(var i=0;i<m.length;i++)
    m[i]=parseInt(m[i]);

var cur=1,t=0;
for(var i=0;i<m.length;i++)
{
    if(m[i]<=cur) t+=(n-cur)+m[i];
    if(m[i]>cur) t+=m[i]-cur;
    cur=m[i];

print(t);
}
print(t);

var n = readline().split(" ").map(function(x) { return parseInt(x); })[0];
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var diff = a[0] - 1;
for (var i = 0; i < a.length - 1; i++) {
	diff += ((a[i+1] >= a[i]) ? (a[i+1] - a[i]) : (n - a[i+1] + a[i] - 2));
}
print (diff);

var n = readline().split(" ").map(function(x) { return parseInt(x); })[1];
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var diff = a[0] - 1;
for (var i = 0; i < a.length - 1; i++) {
	diff += ((a[i+1] >= a[i]) ? (a[i+1] - a[i]) : (a.length - a[i+1] + a[i] - 1));
}
print (diff);

var ringRoad = function(n, arr)
        {
            var counter = arr[0] - 1;
            for (var i = 1; i <= arr.length - 1; i++)
            {
                if (arr[i] > arr[i - 1])
                    {
                         counter += arr[i] - arr[i - 1];
                         continue;
                    }
                else {
					//if (arr[i - 1] !== n)
                    counter += n - arr[i - 1] + arr[i];
					//else counter += 1;
                }
            }
			return counter;
        }
    var toNumArr = function(str)
    {
        str = str.split(' ');
        for (var i = 0 ; i <= str.length - 1; i++)
        {
            str[i] = +str[i];
        }
        return str;
    }
    var num = toNumArr(readline());
    var input = toNumArr(readline());
    print(ringRoad(num[0], input));

 var ringRoad = function(n, arr)
        {
            arr.unshift(1);
            var counter = 0;
            for (var i = 1; i <= arr.length - 1; i++)
            {
                if (arr[i] >= arr[i - 1])
                    {
                         counter += arr[i] - arr[i - 1];

                         continue;
                    }
                else {
					if (arr[i - 1] !== n)
                    counter += n - arr[i - 1] + i;
					else counter += 1;
                }
            }
			return counter;
        }
    var toNumArr = function(str)
    {
        str = str.split(' ');
        for (var i = 0 ; i <= str.length - 1; i++)
        {
            str[i] = +str[i];
        }
        return str;
    }
    var num = toNumArr(readline());
    var input = toNumArr(readline());
    print(ringRoad(num[0], input));

a =readline().split(' ');
b =readline().split(' ');
d = b[0]-1;
for (i=1;i<b.length;i++){
	k = b[i]-b[i-1];
	if (k<0){
		d += a[0]+k;
	}
	else {
		d += k
	}
}
print(d);


Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((i = x1 or i = x2) and (y1 ≤ j ≤ y2)) or ((j = y1 or j = y2) and (x1 ≤ i ≤ x2)).Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them?

The first line contains three space-separated integers n, m and q (1 ≤ n, m, q ≤ 1000) — the height and width of the digital board, and the number of operations. Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai, j — the initial state of pixel (i, j).   If ai, j = 0, pixel (i, j) is initially dark.  If ai, j = 1, pixel (i, j) is initially light.  Then follow q lines, each line containing three space-separated integers op, x, and y (1 ≤ op ≤ 2; 1 ≤ x ≤ n; 1 ≤ y ≤ m), describing an operation.   If op = 1, the pixel at (x, y) changes its state (from light to dark or from dark to light).  If op = 2, Nanami queries the biggest light block with pixel (x, y) on its side.

For each query, print a single line containing one integer — the answer to Nanami's query.

NoteConsider the first sample.The first query specifies pixel (2, 2), which is dark itself, so there are no valid light blocks, thus the answer is 0.The second query specifies pixel (1, 2). The biggest light block is the block with (1, 2) as its upper-left vertex and (1, 3) as its lower-right vertex.The last query specifies pixel (2, 2), which became light in the third operation. The biggest light block is the block with (1, 2) as its upper-left vertex and (3, 3) as its lower-right vertex.


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain.

For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = new Array();
    for (var j = 1; j <= caseLength; j++)
    {
        caseArray.push(j);
    }
    print(caseLength);
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            caseArray[j-1] = caseArray[j];
            caseArray[j] = 1
        }
        var result = "";
        for (var k = 0; k < caseLength; k++)
        {
            result += `${caseArray[k]} `;
        }
        print(result);
    }
}

var n;
    var arr;
    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        n = parseInt(readline());
        arr = new Array(n);
        for (var i = 0; i < n; i++) {
            arr[i] = i+1;
        }
        print(n);
        print(arr.join(' '));
        for (var i = 0; i < n-1; i++) {
            var tmp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = tmp;
            print(arr.join(' '));
        }
    }

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
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';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//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();
	while(hasNext()){
		var N = nextInt();
		var list = new Array(N);
		for(var i = 0; i < N; i++){
			list[i] = i + 1;
		}
		var output = [myconv(list, 8)];
		for(var i = 0; i < N - 1; i++){
			var tmp = list[i];
			list[i] = list[i + 1];
			list[i + 1] = tmp;
			output.push(myconv(list, 8));
		}
		myout(output.length);
		myout(myconv(output, 9));
	}
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', 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 t = +readLine();
    for(let i = 0; i < t; i++){
        const n = +readLine();
        myFunc(n);
        // const arr = readLine().split(' ').map(p => +p);
        // let result = myFunc(n);
        // console.log(result);
    }
}

function myFunc(n){

    let arr = [];
    for(let i = 0; i < n; i++){
        arr[i] = i+1;
    }

    console.log(n);
    console.log(...arr);

    for(let i = 1; i < n; i++){
        [arr[i-1], arr[i]] = [arr[i], arr[i-1]]
        console.log(...arr);
    }

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        output(n);

        let arr = [];
        for (let i = 1; i <= n; i++) {
            arr.push(i);
        }

        let left = 0;
        let right = 1;
        output(arr.join(' '));
        for (let i = 1; i < n; i++) {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            right++;
            output(arr.join(' '));
        }
    }
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = new Array();
    for (var j = 1; j <= caseLength; j++)
    {
        caseArray.push(j);
    }
    print(caseLength);
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            caseArray[j-1] = caseArray[j];
            caseArray[j] = 1
        }
        var result = "";
        for (var k = 0; k < caseLength; k++)
        {
            result += `${k} `;
        }
        print(result);
    }
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = new Array();
    for (var j = 1; j <= caseLength; j++)
    {
        caseArray.push(j);
    }
    print(caseLength);
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            caseArray[j-1] = caseArray[j];
            caseArray[j] = 1
        }
        var result = "";
        for (var k = 0; k < caseLength; k++)
        {
            result += `$k `;
        }
        print(result);
    }
}


Adieu l'ami.Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.The space is represented by a rectangular grid of n × m cells, arranged into n rows and m columns. The c-th cell in the r-th row is denoted by (r, c).Oshino places and removes barriers around rectangular areas of cells. Specifically, an action denoted by "1 r1 c1 r2 c2" means Oshino's placing barriers around a rectangle with two corners being (r1, c1) and (r2, c2) and sides parallel to squares sides. Similarly, "2 r1 c1 r2 c2" means Oshino's removing barriers around the rectangle. Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the n × m area.Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. "3 r1 c1 r2 c2" means that Koyomi tries to walk from (r1, c1) to (r2, c2) without crossing barriers.And you're here to tell Koyomi the feasibility of each of his attempts.

The first line of input contains three space-separated integers n, m and q (1 ≤ n, m ≤ 2 500, 1 ≤ q ≤ 100 000) — the number of rows and columns in the grid, and the total number of Oshino and Koyomi's actions, respectively. The following q lines each describes an action, containing five space-separated integers t, r1, c1, r2, c2 (1 ≤ t ≤ 3, 1 ≤ r1, r2 ≤ n, 1 ≤ c1, c2 ≤ m) — the type and two coordinates of an action. Additionally, the following holds depending on the value of t:    If t = 1: 2 ≤ r1 ≤ r2 ≤ n - 1, 2 ≤ c1 ≤ c2 ≤ m - 1;  If t = 2: 2 ≤ r1 ≤ r2 ≤ n - 1, 2 ≤ c1 ≤ c2 ≤ m - 1, the specified group of barriers exist on the ground before the removal.  If t = 3: no extra restrictions.

For each of Koyomi's attempts (actions with t = 3), output one line — containing "Yes" (without quotes) if it's feasible, and "No" (without quotes) otherwise.

NoteFor the first example, the situations of Koyomi's actions are illustrated below.

 ;(function () {
	var f = new Array();
	for (var i = 0; i <= 2520; i++){
		f[i] = new Array(2521);
		for(var j = 0; j <= 2530; j++)
		    f[i][j]=0;
	}
	var str = readline().split(' '),
		n = +str[0],
		m = +str[1],
		k = +str[2],
		cnt = 0;
	var add = function (a, b, v) {
		for (var i = a; i <= n; i += i & -i)
			for (var j = b; j <= m; j += j & -j)
				f[i][j] = f[i][j] ^ v
	}
	var ask = function (a, b) {
		var ans = 0
		for (var i = a; i; i ^= i & -i)
			for (var j = b; j; j ^= j & -j)
				ans ^= f[i][j]
		return ans
	}
	var update = function (a, b, c, d, e) {
		add(a, b, e);
		add(a, d+1, e);
		add(c+1, b, e);
		add(c+1, d+1, e);
	}
	var hash = function (a, b, c, d) {
		return a * b * c * d;
	}
	while (k --) {
		var line = readline().split(' '),
			op = +line[0],
			x1 = +line[1],
			y1 = +line[2],
			x2 = +line[3],
			y2 = +line[4],
			id = hash(x1, y1, x2, y2);
		if (op == 1) {
			update(x1, y1, x2, y2, id);
		} else if (op == 2) {
			update(x1, y1, x2, y2, id);
		} else {
			print(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');
			// print(ask(x1, y1))
			// print(ask(x2, y2))
		}
	}
})();

 ;(function () {
	var f = new Array();
	for (var i = 0; i <= 2520; i++){
		f[i] = new Array(2521);
		for(var j = 0; j <= 2520; j++)
		    f[i][j]=0;
	}
	var str = readline().split(' '),
		n = +str[0],
		m = +str[1],
		k = +str[2],
		cnt = 0;
	var add = function (a, b, v) {
		for (var i = a; i <= n; i += i & -i)
			for (var j = b; j <= m; j += j & -j)
				f[i][j] = f[i][j] ^ v
	}
	var ask = function (a, b) {
		var ans = 0
		for (var i = a; i; i ^= i & -i)
			for (var j = b; j; j ^= j & -j)
				ans ^= f[i][j]
		return ans
	}
	var update = function (a, b, c, d, e) {
		add(a, b, e);
		add(a, d+1, e);
		add(c+1, b, e);
		add(c+1, d+1, e);
	}
	var hash = function (a, b, c, d) {
		return a * b * c * d;
	}
	while (k --) {
		var line = readline().split(' '),
			op = +line[0],
			x1 = +line[1],
			y1 = +line[2],
			x2 = +line[3],
			y2 = +line[4],
			id = hash(x1, y1, x2, y2);
		if (op == 1) {
			update(x1, y1, x2, y2, id);
		} else if (op == 2) {
			update(x1, y1, x2, y2, id);
		} else {
			print(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');
			// print(ask(x1, y1))
			// print(ask(x2, y2))
		}
	}
})();

;(function () {
	var f = new Array();
	for (var i = 1; i <= 2520; i++)
		f[i] = new Array(2521).join(0).split('')
	var str = readline().split(' '),
		n = +str[0],
		m = +str[1],
		k = +str[2],
		cnt = 0;
	var add = function (a, b, v) {
		for (var i = a; i <= n; i += i & -i)
			for (var j = b; j <= m; j += j & -j)
				f[i][j] = +f[i][j] + v
	}
	var ask = function (a, b) {
		var ans = 0
		for (var i = a; i; i ^= i & -i)
			for (var j = b; j; j ^= j & -j)
				ans += +f[i][j]
		return ans
	}
	var update = function (a, b, c, d, e) {
		add(a, b, e);
		add(a, d+1, -e);
		add(c+1, b, -e);
		add(c+1, d+1, e);
	}
	var hash = function (a, b, c, d) {
		return a * b * c * d;
	}
	while (k --) {
		var line = readline().split(' '),
			op = +line[0],
			x1 = +line[1],
			y1 = +line[2],
			x2 = +line[3],
			y2 = +line[4],
			id = hash(x1, y1, x2, y2);
		if (op == 1) {
			update(x1, y1, x2, y2, id);
		} else if (op == 2) {
			update(x1, y1, x2, y2, -id);
		} else {
			print(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');
			// print(ask(x1, y1))
			// print(ask(x2, y2))
		}
	}
})();

;(function () {
	var f = new Array();
	for (var i = 1; i <= 2520; i++)
		f[i] = new Array(2521).join(0).split('')
	var str = readline().split(' '),
		n = +str[0],
		m = +str[1],
		k = +str[2],
		cnt = 0;
	var add = function (a, b, v) {
		for (var i = a; i <= n; i += i & -i)
			for (var j = b; j <= m; j += j & -j)
				f[i][j] = +f[i][j] ^ v
	}
	var ask = function (a, b) {
		var ans = 0
		for (var i = a; i; i ^= i & -i)
			for (var j = b; j; j ^= j & -j)
				ans ^= +f[i][j]
		return ans
	}
	var update = function (a, b, c, d, e) {
		add(a, b, e);
		add(a, d+1, e);
		add(c+1, b, e);
		add(c+1, d+1, e);
	}
	var hash = function (a, b, c, d) {
		return a * b * c * d;
	}
	while (k --) {
		var line = readline().split(' '),
			op = +line[0],
			x1 = +line[1],
			y1 = +line[2],
			x2 = +line[3],
			y2 = +line[4],
			id = hash(x1, y1, x2, y2);
		if (op == 1) {
			update(x1, y1, x2, y2, id);
		} else if (op == 2) {
			update(x1, y1, x2, y2, id);
		} else {
			print(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');
			// print(ask(x1, y1))
			// print(ask(x2, y2))
		}
	}
})();

;(function () {
	var f = new Array();
	for (var i = 1; i <= 2520; i++)
		f[i] = new Array(2521).join(0).split('')
	var str = readline().split(' '),
		n = +str[0],
		m = +str[1],
		k = +str[2],
		cnt = 0;
	var add = function (a, b, v) {
		for (var i = a; i <= n; i += i & -i)
			for (var j = b; j <= n; j += j & -j)
				f[i][j] = +f[i][j] + v
	}
	var ask = function (a, b) {
		var ans = 0
		for (var i = a; i; i ^= i & -i)
			for (var j = b; j; j ^= j & -j)
				ans += +f[i][j]
		return ans
	}
	var update = function (a, b, c, d, e) {
		add(a, b, e);
		add(a, d+1, -e);
		add(c+1, b, -e);
		add(c+1, d+1, e);
	}
	var hash = function (a, b, c, d) {
		return a * b * c * d;
	}
	while (k --) {
		var line = readline().split(' '),
			op = +line[0],
			x1 = +line[1],
			y1 = +line[2],
			x2 = +line[3],
			y2 = +line[4],
			id = hash(x1, y1, x2, y2);
		if (op == 1) {
			update(x1, y1, x2, y2, id);
		} else if (op == 2) {
			update(x1, y1, x2, y2, -id);
		} else {
			print(ask(x1, y1) === ask(x2, y2) ? 'Yes' : 'No');
			// print(ask(x1, y1))
			// print(ask(x2, y2))
		}
	}
})();

;(function () {
	var f = new Array();
	for (var i = 1; i <= 2520; i++)
		f[i] = new Array(2521).join(0).split('')
	var str = readline().split(' '),
		n = +str[0],
		m = +str[1],
		k = +str[2],
		cnt = 0;
	var add = function (a, b, v) {
		for (var i = a; i <= n; i += i & -i)
			for (var j = b; j <= n; j += j & -j)
				f[i][j] = +f[i][j] + v
	}
	var ask = function (a, b) {
		var ans = 0
		for (var i = a; i; i ^= i & -i)
			for (var j = b; j; j ^= j & -j)
				ans += +f[i][j]
		return ans
	}
	var update = function (a, b, c, d, e) {
		add(a, b, e);
		add(a, d+1, -e);
		add(c+1, b, -e);
		add(c+1, d+1, e);
	}
	var hash = function (a, b, c, d) {
		return a * b * c * d;
	}
	while (k --) {
		var line = readline().split(' '),
			op = +line[0],
			x1 = +line[1],
			y1 = +line[2],
			x2 = +line[3],
			y2 = +line[4],
			id = hash(x1, y1, x2, y2);
		if (op == 1) {
			update(x1, y1, x2, y2, id);
		} else if (op == 2) {
			update(x1, y1, x2, y2, -id);
		} else {
			print(ask(x1, y1) === ask(x2, y2) ? 'YES' : 'NO');
			// print(ask(x1, y1))
			// print(ask(x2, y2))
		}
	}
})();


In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.A string is a bHTML table, if it satisfies the grammar: TABLE ::=
ROWS
ROWS ::= ROW | ROW ROWSROW ::=
CELLS
CELLS ::= CELL | CELL CELLSCELL ::= 	 | TABLE	Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.

For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.

Print the sizes of all the tables in the non-decreasing order.

'use strict'

let ht = ''
let j = 10

while (j--) {
  ht += readline() || ''
}

let tst = []
let ts = []

for (let i = 0; i < ht.length; i++) {
  if (ht.slice(i,  i + 7) == '<table>') {
    tst.push(0)
  } else if (ht.slice(i,  i + 8) == '</table>') {
    ts.push(tst.pop())
  } else if (ht.slice(i,  i + 4) == '<td>') {
    tst[tst.length - 1]++
  }
}

print(ts.sort((a, b) => a - b).join(' '))


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$  — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if(sum!==0) return 'NO'
  while(a.length && !a[a.length-1])a.pop()
  if(a[0]){
    while(a.length>1){
      const last=a.length-1
      if(a[last]>=0)return 'NO'
      a[last-1]+=a.pop()
    }
  }else if(a.length){
    return 'NO'
  }
  return 'YES'
}

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

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

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  {
    let sum = 0,
        flag = false;
    for (let i = 0; i < n ; i++) {
      sum += a[i];
      if (sum < 0) return 'NO';
      if (flag && sum !== 0) return 'NO';
      if (sum === 0) flag = true;
    }
    if(sum!==0)return 'NO'
  }
  return 'YES';
}

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

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

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if (sum !== 0) return 'NO';
  //if (n <= 2) return 'YES';
  {
    let sum = 0,
        flag = false;
    for (let i = 0; i < n - 1; i++) {
      sum += a[i];
      if (sum < 0) return 'NO';
      if (flag && sum !== 0) return 'NO';
      if (sum === 0) flag = true;
    }
  }
  return 'YES';
}

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

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

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = Number(lines[i]);
        }else{
            var a = lines[i].split(' ').map(Number);
            var flag = false;
            var x = 0;
            for(j = 0; j < n; j++){
                if(a[j] + x < 0){
                    flag = true;
                }
                if(j && a[j] > 0 && x === 0){
                    flag = true;
                }
                x = a[j] + x;
            }
            if(x !== 0){
                flag = true;
            }
            if(flag){
                console.log('NO');
            }else{
                console.log('YES');
            }
        }
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let i = 0; i < N; i++) {
        let size = Number(readline());
        let arr = readline().split(' ').map(Number);
        let jumpsToTheRight = new Array(size).fill(0);
        jumpsToTheRight[0] = arr[0];
        let sum = arr[0];
        for (let index = 1; index < jumpsToTheRight.length; index++) {
            jumpsToTheRight[index] = arr[index] + jumpsToTheRight[index - 1];
            sum += arr[index];
        }

        let result = 'yes';
        let zero = false;
        for (let jumps of jumpsToTheRight) {
            if (jumps < 0) {
                result = 'no';
                break;
            } else if (jumps === 0) {
                zero = true;
            } else if (zero) {
                result = 'no';
                break;
            }
        }

        if (sum !== 0) {
            result = 'no';
        }

        output(result);
    }
}

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if(sum!==0) return 'NO'
  while(a.length && !a[a.length-1])a.pop()
  if(a[0]){
    while(a.length>1){
      const last=a.length-1
      if(a[last]>0)return 'NO'
      a[last-1]+=a.pop()
    }
  }else if(a.length){
    return 'NO'
  }
  return 'YES'
}

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

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

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if(sum!==0) return 'NO'
  while(a.length && !a[a.length-1])a.pop()
  if(a[0]){
    while(a.length>1){
      console.log(a)
      const last=a.length-1
      if(a[last]>0)return 'NO'
      a[last-1]+=a.pop()
    }
  }else if(a.length){
    return 'NO'
  }
  return 'YES'
}

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

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

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if(sum!==0) return 'NO'
  a.reverse()
  while(a.length>1){
    const last=a.length-1
    if(a[last]<0 || a[last]<a[last-1])return 'NO'
    a[last-1]+=a.pop()
  }
  return 'YES'
}

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

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

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if(sum!==0)return 'NO'
  {
    let sum = 0
    for (let i = 0; i < n ; i++) {
      sum += a[i];
      if (sum < 0) return 'NO';
    }
  }
  return 'YES';
}

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

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

'use strict';

function solve(n, a) {
  {
    let sum = 0,
        flag = false;
    for (let i = 0; i < n - 1; i++) {
      sum += a[i];
      if (sum < 0) return 'NO';
      if (flag && sum !== 0) return 'NO';
      if (sum === 0) flag = true;
    }
    if(sum!==0)return 'NO'
  }

  return 'YES';
}

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

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

'use strict';

function solve(n, a) {
  {
    let sum = 0,
        flag = false;
    for (let i = 0; i < n - 1; i++) {
      sum += a[i];
      if (sum < 0) return 'NO';
      if (flag && sum !== 0) return 'NO';
      if (sum === 0) flag = true;
    }
  }
  return 'YES';
}

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

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

'use strict';

function solve(n, a) {
  const sum = a.reduce((a, b) => a + b);
  if (sum !== 0) return 'NO';
  if (n <= 2) return 'YES';
  {
    let sum = 0,
        flag = false;
    for (let i = 0; i < n - 1; i++) {
      sum += a[i];
      if (sum < 0) return 'NO';
      if (flag && sum !== 0) return 'NO';
      if (sum === 0) flag = true;
    }
  }
  return 'YES';
}

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

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


There are $$$n$$$ heaps of stone. The $$$i$$$-th heap has $$$h_i$$$ stones. You want to change the number of stones in the heap by performing the following process once:   You go through the heaps from the $$$3$$$-rd heap to the $$$n$$$-th heap, in this order.  Let $$$i$$$ be the number of the current heap.  You can choose a number $$$d$$$ ($$$0 \le 3 \cdot d \le h_i$$$), move $$$d$$$ stones from the $$$i$$$-th heap to the $$$(i - 1)$$$-th heap, and $$$2 \cdot d$$$ stones from the $$$i$$$-th heap to the $$$(i - 2)$$$-th heap.  So after that $$$h_i$$$ is decreased by $$$3 \cdot d$$$, $$$h_{i - 1}$$$ is increased by $$$d$$$, and $$$h_{i - 2}$$$ is increased by $$$2 \cdot d$$$.  You can choose different or same $$$d$$$ for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$). The second lines of each test case contains $$$n$$$ integers $$$h_1, h_2, h_3, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum number of stones that the smallest heap can contain.

NoteIn the first test case, the initial heap sizes are $$$[1, 2, 10, 100]$$$. We can move the stones as follows.   move $$$3$$$ stones and $$$6$$$ from the $$$3$$$-rd heap to the $$$2$$$-nd and $$$1$$$ heap respectively. The heap sizes will be $$$[7, 5, 1, 100]$$$;  move $$$6$$$ stones and $$$12$$$ stones from the last heap to the $$$3$$$-rd and $$$2$$$-nd heap respectively. The heap sizes will be $$$[7, 17, 7, 82]$$$. In the second test case, the last heap is $$$1$$$, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be $$$[3, 5, 3, 4, 3, 3]$$$.

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const h = (await getLine()).split(' ').map(num => parseInt(num));
        let l = 0, r = 0;
        let best = 0;
        for(let i = 0; i < n; i++)
            r = Math.max(r, h[i]);
        const workh = new Array(n);

        const resolve = function(th) {
            for(let i = 0; i < n; i++)
                workh[i] = 0;

            for(let i = n - 1; i >=0; i--) {
                if (h[i] + workh[i] < th)
                    return false;
                const rem = h[i] + workh[i] - th;
                if (i>=2) {
                    workh[i - 1] += Math.floor(Math.min(h[i], rem) / 3);
                    workh[i - 2] += Math.floor(Math.min(h[i], rem) / 3) * 2;
                }
            }

            return true;
        }

        while (l <= r) {
            const mid = Math.floor((l+r) / 2);
            if (resolve(mid)) {
                best = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }

        console.log(best);
    }
}

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--) {
		const n = rn();
		const h = rna();

		function check (x) {
			const hh = h.slice();
			for (let i = n-1; i >= 2; i--) {
				if (hh[i] < x)
					return false;
				let d = Math.floor((hh[i]-x)/3);
				d = Math.min(Math.floor(h[i]/3), d);
				hh[i] -= 3*d;
				hh[i-1] += d;
				hh[i-2] += 2*d;
			}
			return hh[0] >= x && hh[1] >= x;
		}

		let l = 1, r = 1e9;
		while (r-l > 1) {
			let m = l + r >> 1;
			if (check(m)) {
				l = m;
			} else {
				r = m-1;
			}
		}

		const ans = check(r) ? r : l;

		console.log(ans);
	}
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function solve_one_test() {
  let n = parseInt(readline());
  let array = readline().split(" ").map(x => parseInt(x));
  // console.log(array);

  let low = 0;
  let high = 1e9 + 1;

  while (low + 1 != high) {
    let mid = Math.floor((low + high) / 2);

    function can_do(min_element) {
      carry = 0;
      carry_next = 0;

      for (let i = n - 1; i >= 0; --i) {
        let need_move = Math.floor((array[i] + carry - min_element) / 3);
        need_move = Math.min(need_move, Math.floor(array[i] / 3));

        if (i <= 1) {
          need_move = 0;
        }

        if (need_move < 0) {
          need_move = 0;
        }

        if (array[i] + carry - need_move * 3 < min_element) {
          return false;
        }

        carry = carry_next;
        carry_next = 0;

        carry += need_move;
        carry_next += need_move * 2;
      }

      if (carry > 0 || carry_next > 0) {
        return false;
      }

      return true;
    };

    if (can_do(mid)) {
      low = mid;
    } else {
      high = mid;
    }
  }

  console.log(low)
}

function main() {
  let num_tests = parseInt(readline());

  for (let i = 0; i < num_tests; ++i) {
    solve_one_test();
  }
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const h = (await getLine()).split(' ').map(num => parseInt(num));
        let l = 0, r = 0;
        let best = 0;
        for(let i = 0; i < n; i++)
            r = Math.max(r, h[i]);
        const workh = new Array(n);

        const resolve = function(th) {
            for(let i = 0; i < n; i++)
                workh[i] = 0;

            for(let i = n - 1; i >=0; i--) {
                if (h[i] + workh[i] < th)
                    return false;
                const rem = h[i] + workh[i] - th;
                if (i > 0) {
                   workh[i-1] += Math.floor(Math.min(h[i], rem)/3);
                }
                if (i > 1)
                    workh[i-2] += Math.floor(Math.min(h[i], rem)/3) * 2;
            }

            return true;
        }

        while (l <= r) {
            const mid = Math.floor((l+r) / 2);
            if (resolve(mid)) {
                best = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }

        console.log(best);
    }
}

solve();