You are given two integers $$$l$$$ and $$$r$$$, $$$l\le r$$$. Find the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.As a reminder, $$$a \bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \bmod 8 = 2$$$.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\le t\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\le l \le r \le 10^9$$$).

For every test case, output the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.

NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \bmod b = 1 \bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \bmod b = 1$$$.

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number)
        var l = k[0]
        var r = k[1]
        var a = r;
        var b = Math.max(l, Math.floor(r / 2) + 1);
        console.log(a % b);
    }

});

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ************************ Code Start ***************************

function main() {

  var t=parseInt(readline());

while(t--){
    let ar=readline().split(' ').map(x=>parseInt(x));

    let l=ar[0];
    let r=ar[1];

    if(r<l*2){
        print(r-l);
    }else{
        print(Math.floor((r-1)/2));
    }
}

}

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

let testCase = true;

rl.on('line', function(line){
   if(testCase || line.length === 0) {
     testCase = false;
     return;
   }

   const [a, b] = line.split(" ").map((n) => parseInt(n))

   let half;
   if(b % 2 === 0) {
    half = b / 2;
   } else {
     half = (b - 1) / 2;
   }

  const ans = (b - Math.min(b, Math.max(a, half + 1)))
  console.log(ans)
})

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

let testCase = true;

rl.on('line', function(line){
   if(testCase) {
     testCase = false;
     return;
   }

   const [a, b] = line.split(/ +/).map((n) => parseInt(n))
  //  console.log(a, b)
   let half;
   if(b % 2 === 0) {
    half = b / 2;
   } else {
     half = (b - 1) / 2;
   }

   const ans = (b - Math.min(b, Math.max(a, half + 1)))
   if( ans === NaN) {
     console.log(a + '*' + b)
   } else {
     console.log(ans)
   }
})

// var t = Number(readline());
// var ans;
// for (var i = 1; i <= t; i++) {
//     var arr = readline().split(' ').map(x => parseInt(x));
//     var l = arr[0],
//         r = arr[1];

//     var a = parseInt((r / 2) + 1);

//     if (a >= l) {
//         ans = r % a;

//     } else {
//         ans = r % l;

//     }
//     console.log(ans);
// }

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

function print(x) {
    console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});

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

// ************************ Code Start ***************************

function main() {

    var t = Number(readline());
    var ans;
    for (var i = 1; i <= t; i++) {
        var arr = readline().split(' ').map(x => parseInt(x));
        var l = arr[0],
            r = arr[1];

        var a = parseInt((r / 2) + 1);

        if (a >= l) {
            ans = r % a;

        } else {
            ans = r % l;

        }
        console.log(ans);
    }

}

'use strict'

function beginAndGetInputData() {
    let i = ''
    let lines = [];
    process.stdin.on('data', c => i += c)
    process.stdin.on('end', () => {
        lines = i.split('\n'); // your input text, split by lines
        if (lines[lines.length - 1].length === 0) {
            lines.length--;
        };
        main(lines);
    });
}

function main(lines) {
    // let r = 999999999;
    // let ans = Math.ceil((r + 1) / 2);
    // console.log(r % (ans +1));
    for (let i = 1; i < lines.length; i++){
        let line = lines[i].split(' ');
        let l = parseInt(line[0]), r = parseInt(line[1]);
        let ans = Math.ceil((r + 1) / 2);
        console.log(r % Math.max(l, ans));
    }
}

beginAndGetInputData();

let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var k = lines[i].split(' ').map(Number);
        var l = k[0], r = k[1];
        var a = r;
        var b = Math.max(l, Math.floor(r / 2) + 1);
        console.log(a % b);
    }
});

let line = '';
process.stdin.on('data', c => line += c);
process.stdin.on('end', () => {
    let input = line.trim().split('\n');
    for (let i = 1; i < input.length; ++i) {
        let [l, r] = input[i].split(' ').map(x => Number(x));
        console.log(l <= Math.floor(r / 2 + 1) ? r % Math.floor(r / 2 + 1) : r % l);
    }
});

var fs = require('fs'), currentline = 0, input = fs.readFileSync(0, 'utf8').trim().split('\n');
function readline() { return input[currentline++]; }
var T = +readline();
for (var j = 0; j < T; j++) {
    var n = readline().split(' ').map(function (x) { return Number(x); });
    var ans = Math.min(n[1] - n[0], Math.floor((n[1] + 1) / 2) - 1);
    console.log(ans);
}

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

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

function main () {
	let T = rn();
	while (T--) {
		let [l, r] = rna();

		const a = r;
		const b = Math.max(l, Math.ceil((a+1)/2));

		console.log(a%b);
	}
}

//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] = BigInt(next());
		}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 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 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 L = nextInt();
		var R = nextInt();
		myout(R % Math.max(L, Math.ceil((R + 1) / 2)));
	}
}

'use strict'
var os = require('os')
function createInput(t) {
  const n = t.stdin || process.stdin,
    e = /-?\d+/g,
    r = /-?\d+(?:\.\d+)?/g
  let u = [],
    o = 0
  return {
    init: async function () {
      const t = []
      ;(u = await new Promise(e => {
        n.on('data', n => t.push(n)),
          n.on('end', function () {
            const n = t.join('').split(os.EOL)
            e(n)
          })
      })),
        (o = 0)
    },
    dried: function () {
      return o >= u.length
    },
    readLine: i,
    readLineAsNumber: function () {
      return Number(i())
    },
    readIntegersOfLine: function () {
      const t = i().match(e)
      return null == t ? [] : t.map(t => Number(t))
    },
    readNumsOfLine: function () {
      const t = i().match(r)
      return null == t ? [] : t.map(t => Number(t))
    },
  }
  function i() {
    return u[o++]
  }
}
function createOutput(t) {
  const n = t.stdout || process.stdout,
    e = t.encoding || 'ascii',
    r = t.outputBufferThreshold || 1 << 24,
    u = Buffer.alloc(r)
  let o = 0
  return {
    flush: i,
    print: function (t) {
      s('string' == typeof t ? t : t.toString())
    },
    println: function (t) {
      s(('string' == typeof t ? t : t.toString()).concat('\n'))
    },
  }
  function i() {
    n.write(u.toString(e, 0, o)), (o = 0)
  }
  function s(t) {
    const s = Buffer.byteLength(t, e)
    r - o < s && (i(), s >= r) ? n.write(t) : (u.write(t, o, e), (o += s))
  }
}
function createInputAndOutput(t) {
  return {
    ...createInput({ stdin: t.stdin, encoding: t.encoding }),
    ...createOutput({
      stdout: t.stdout,
      encoding: t.encoding,
      outputBufferThreshold: t.outputBufferThreshold,
    }),
  }
}
async function __main__(t, n, e = {}) {
  const r = createInputAndOutput(e)
  await Promise.all([r.init(), Promise.resolve(n && n())]),
    await t(r),
    r.flush()
}
__main__(function (t) {
  const n = t.readLineAsNumber()
  for (let e = 1; e <= n; ++e) {
    const [n, e] = t.readIntegersOfLine()
    let r = 1 + (e >> 1)
    r < n && (r = n)
    const u = e % r
    t.print(u + '\n')
  }
})

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number)
        var l = k[0]
        var r = k[1]
        var a = r;
        var b = Math.max(l, Math.floor(r / 2) - 1);
        console.log(a % b);
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number)
        var l = k[0]
        var r = k[1]
         a = r;
        var b = Math.max(l, Math.floor(r / 2) - 1);
        console.log(a % b);
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number)
        var l = k[0]
        var r = k[1]
         a = r;
        var b = Math.max(l, Math.ceil(r / 2) - 1);
        console.log(a % b);
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number)
        var l = k[0]
        var r = k[1]
         a = r;
        var b = Math.max(l, Math.ceil(r / 2));
        console.log(a % b);
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j].split(' ').map(Number)
        var l = k[0]
        var r = k[1]
         a = r;
        var b = Math.max(l, Math.floor(r / 2));
        console.log(a % b);
    }

});

let i = '';

process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    var answer = 0
    var v = 0
    for(j = 1; j <= n; j++){
        var s = lines[j].split(' ').map(Number)
        var a = s[0]
        var b = s[1]
        if(Math.max(a, b) / 2 > Math.min(a, b)){
            answer = Math.max(a, b) / 2
            v = Math.ceil(answer - 1)
            console.log(v)
        }else{
    answer = Math.floor((a + b) / 2 )
        v = Math.max(a, b) % answer
        console.log(v)
        }
    }
});

let i = '';

process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    var answer = 0
    var v = 0
    for(j = 1; j <= n; j++){
        var s = lines[j].split(' ').map(Number)
        var a = s[0]
        var b = s[1]
        answer = (a + b) / 2
        v = Math.max(a, b) % answer
        console.log(v)
    }
});

let i = '';

process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    var answer = 0
    var v = 0
    for(j = 1; j <= n; j++){
        var s = lines[j].split(' ').map(Number)
        var a = s[0]
        var b = s[1]
        answer = (a + b) / 2
        v = Math.max(a, b) / answer
        console.log(v)
    }
});

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ************************ Code Start ***************************

function main() {

  var t=parseInt(readline());

    let ar=readline().split(' ').map(x=>parseInt(x));

    let l=ar[0];
    let r=ar[1];

    if(r<l*2){
        print(r-l);
    }else{
        print(Math.floor((r-1)/2));
    }

}

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();
    t = parseInt(t);
    while(t--) {
        let l=parseInt(readLine())
    let r=parseInt(readLine())

    if(r<l*2){
        console.log(r-l)
    }
    else{
        console.log(Math.floor((r-1)/2))
    }
    }
}

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

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

function main() {
    var t=parseInt(readline());

    while(t--){
    var l=parseInt(readline());
    var r=parseInt(readline());

    if(r<l*2){
        console.log(r-l);
    }
    else{
        console.log(Math.floor((r-1)/2));
    }

}

}

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

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

function main() {
    var t=parseInt(readline())

    while(t--){
    var l=parseInt(readline())
    var r=parseInt(readline())

    if(r<l*2){
        console.log(r-l)
    }
    else{
        console.log(Math.floor((r-1)/2))
    }

}

}

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

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

function main() {
    var t=parseInt(readline())

while(t--){
    var l=parseInt(readline())
    var r=parseInt(readline())

    if(r<l*2){
        print(r-l)
    }
    else{
        print(Math.floor((r-1)/2))
    }

}

}

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

let testCase = true;

rl.on('line', function(line){
   if(testCase) {
     testCase = false;
     return;
   }

   const [a, b] = line.split(/ +/).map((n) => parseInt(n))
  //  console.log(a, b)
   let half;
   if(b % 2 === 0) {
    half = b / 2;
   } else {
     half = (b - 1) / 2;
   }

   console.log(b - Math.min(b, Math.max(a, half + 1)))
})

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

let testCase = true;

rl.on('line', function(line){
   if(testCase) {
     testCase = false;
     return;
   }

   const [a, b] = line.split(" ").map((n) => parseInt(n))
  //  console.log(a, b)
   let half;
   if(b % 2 === 0) {
    half = b / 2;
   } else {
     half = (b - 1) / 2;
   }

   console.log(b - Math.min(b, Math.max(a, half + 1)))
})

// var t = Number(readline());
// var r;
// for (var i = 1; i <= t; i++) {
//     var arr = readline().split(' ').map(x => parseInt(x));
//     var a = arr[0],
//         b = arr[1];

//     if (a >= b) {
//         r = a % b;
//         if (r == 1) {
//             r = 1;
//         } else {
//             r = parseInt(((a - r) / 2));
//         }
//     } else {
//         r = b % a;
//         if (r == 1) {
//             r = 1;
//         } else {
//             r = parseInt(((b - r) / 2));
//         }
//     }
//     console.log(r);
// }

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

function print(x) {
    console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});

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

// ************************ Code Start ***************************

function main() {

    var t = Number(readline());
    var r;
    for (var i = 1; i <= t; i++) {
        var arr = readline().split(' ').map(x => parseInt(x));
        var a = arr[0],
            b = arr[1];

        if (a >= b) {
            r = a % b;
            if (r == 1) {
                r = 1;
            } else {
                r = parseInt(((a - r) / 2));
            }
        } else {
            r = b % a;
            if (r == 1) {
                r = 1;
            } else {
                r = parseInt(((b - r) / 2));
            }
        }
        console.log(r);
    }

}

// var t = Number(readline());
// var r;
// for (var i = 1; i <= t; i++) {
//     var arr = readline().split(' ').map(x => parseInt(x));
//     var a = arr[0],
//         b = arr[1];

//     if (a >= b) {
//         r = a % b;
//     } else {
//         r = b % a;
//     }
//     console.log(r);
// }

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

function print(x) {
    console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});

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

// ************************ Code Start ***************************

function main() {

    var t = Number(readline());
    var r;
    for (var i = 1; i <= t; i++) {
        var arr = readline().split(' ').map(x => parseInt(x));
        var a = arr[0],
            b = arr[1];

        if (a >= b) {
            r = a % b;
        } else {
            r = b % a;
        }
        console.log(r);
    }
}

'use strict'

function beginAndGetInputData() {
    let i = ''
    let lines = [];
    process.stdin.on('data', c => i += c)
    process.stdin.on('end', () => {
        lines = i.split('\n'); // your input text, split by lines
        main(lines);
    });
}

function main(lines) {
    // let r = 999999999;
    // let ans = Math.ceil((r + 1) / 2);
    // console.log(r % (ans +1));
    for (let i = 1; i < lines.length; i++){
        let line = lines[i].split(' ');
        let l = parseInt(line[0]), r = parseInt(line[1]);
        let ans = Math.ceil((r + 1) / 2);
        console.log(r % Math.max(l, ans));
    }
}

beginAndGetInputData();


This is the hard version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$2n$$$ operations. It can be proved that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output an integer $$$k$$$ ($$$0\le k\le 2n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.

NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.

function not(c) {
   if (c === '1') {
      return '0';
   }
   return '1';
}

function inc(i) {
   return i + 1;
}

function dec(i) {
   return i  - 1;
}

function solve() {
   var n = Number(read());
   var a = Array.from(read());
   var b = Array.from(read());
   var ans = [];

   function f(index) {
      var res = a.slice();
      for (var i = 0; i <= index; i++) {
         res[i] = not(a[index - i]);
      }
      a = res;
   }

   var rev = false;
   var j = n - 1;
   var from = n - 1;
   var to = 0;
   var f = dec;
   for (var i = n - 1; i >= 0; i--) {
      var curA = a[j];
      var zeroA = a[to];
      if (rev) {
         curA = not(curA);
         zeroA = not(zeroA);
      }
      if (curA === b[i]) {
         j = f(j);
         from = j;
         continue;
      }
      if (zeroA === b[i]) {
         ans.push(1);
         a[to] = not(a[to]);
      }
      ans.push(i + 1);
      if (rev) {
         rev = false;
         f = dec;
      } else {
         rev = true;
         f = inc;
      }
      j = f(to);
      to = from;
      from = j;
   }
   write(ans.length + ' ' + ans.join(' '));
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

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

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

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

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

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() {
    const t = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        let a = Array.from(readLine()).map(Number)
        const b = Array.from(readLine()).map(Number)
        const results = []
        let start = 0, reverse = false
        for (let i = n - 1; i >= 0; i--) {
          if (reverse ? a[start - i] !== b[i] : a[start + i] === b[i]) {
            continue
          }
          if (i === 0) {
            if (reverse ? a[start] === b[0] : a[start] !== b[0]) {
              results.push(1)
            }
            continue
          }
          if (reverse ? a[start] !== b[i] : a[start] === b[i]) {
            results.push(1)
            a[start] = (a[start] + 1) % 2
          }
          results.push(i + 1)
          start = reverse ? start - i : start + i
          reverse = !reverse
        }
      console.log(`${results.length}${results.length ? ' ' + results.join(' ') : ''}`)
    }
}

'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++]
}

String.prototype.count = function(c) {
  let result = 0
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++
  return result
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1)
}

function main() {
  let t = readLine()
  t = parseInt(t)

  while(t--) {
    let n = parseInt(readLine().trim())
    let [a, b] = [readLine().trim(), readLine().trim()]

    a += '0'
    b += '0'

    let [ops1, ops2] = [[], []]

    for (let i = 1; i <= n; ++i) {
      if (a[i] !== a[i-1])
        ops1.push(i)

      if (b[i] !== b[i-1])
        ops2.push(i)
    }

    ops2.reverse()
    ops1 = ops1.concat(ops2)

    process.stdout.write(ops1.length + ' ')
    for(let o of ops1)
      process.stdout.write(o + ' ')
    process.stdout.write('\n')
  }
}

function not(c) {
   if (c === '1') {
      return '0';
   }
   return '1';
}

function inc(i) {
   return i + 1;
}

function dec(i) {
   return i  - 1;
}

function solve() {
   var n = Number(read());
   var a = Array.from(read());
   var b = Array.from(read());
   var ans = [];

   var rev = false;
   var j = n - 1;
   var from = n - 1;
   var to = 0;
   var f = dec;
   var t;
   for (var i = n - 1; i >= 0; i--) {
      var curA = a[j];
      var zeroA = a[to];
      if (rev) {
         curA = not(curA);
         zeroA = not(zeroA);
      }
      write(j + ' ' + from + ' ' + to);
      if (curA === b[i]) {
         j = f(j);
         from = j;
         continue;
      }
      if (zeroA === b[i]) {
         ans.push(1);
         a[to] = not(a[to]);
      }
      ans.push(i + 1);
      if (rev) {
         rev = false;
         f = dec;
      } else {
         rev = true;
         f = inc;
      }
      j = to;
      to = from;
      from = j;
      j = f(j);
   }
   write(ans.length + ' ' + ans.join(' '));
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

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

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

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

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

function not(c) {
   if (c === '1') {
      return '0';
   }
   return '1';
}

function inc(i) {
   return i + 1;
}

function dec(i) {
   return i  - 1;
}

function solve() {
   var n = Number(read());
   var a = Array.from(read());
   var b = Array.from(read());
   var ans = [];

   var rev = false;
   var j = n - 1;
   var from = n - 1;
   var to = 0;
   var f = dec;
   var t;
   for (var i = n - 1; i >= 0; i--) {
      var curA = a[j];
      var zeroA = a[to];
      if (rev) {
         curA = not(curA);
         zeroA = not(zeroA);
      }
      if (curA === b[i]) {
         j = f(j);
         from = j;
         continue;
      }
      if (zeroA === b[i]) {
         ans.push(1);
         a[to] = not(a[to]);
      }
      ans.push(i + 1);
      if (rev) {
         rev = false;
         f = dec;
      } else {
         rev = true;
         f = inc;
      }
      j = to;
      to = from;
      from = j;
      j = f(j);
   }
   write(ans.length + ' ' + ans.join(' '));
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

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

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

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

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

'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++]
}

String.prototype.count = function(c) {
  let result = 0
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++
  return result
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1)
}

function main() {
  let t = readLine()
  t = parseInt(t)

  while(t--) {
    let n = parseInt(readLine().trim())
    let [a, b] = [readLine().trim(), readLine().trim()]

    a += '0'
    b += '0'

    let [ops1, ops2] = [[], []]

    for (let i = 1; i <= n; ++i) {
      if (a[i] !== a[i-1])
        ops1.push(i)

      if (b[i] !== b[i-1])
        ops2.push(i)
    }

    ops2.reverse()
    ops1 = ops1.concat(ops2)

    process.stdout.write(String(ops1.length))
    for(let o of ops1)
      process.stdout.write(String(o))
  }
}


You have a string $$$s_1 s_2 \ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \le k \le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the lexicographically smallest string you can see.

4
10
codeforces
9
cbacbacba
3
aaa
4
bbaa

NoteIn the first test case choose $$$k = 1$$$ to obtain "cc".In the second test case choose $$$k = 3$$$ to obtain "cbaabc".In the third test case choose $$$k = 1$$$ to obtain "aa".In the fourth test case choose $$$k = 1$$$ to obtain "bb".

const solve = (n,str)=>{
     let k = 1,p = str[0];
     if(n===1){
          console.log(str[0]+str[0]);
          return;
     }
     if(str[0]===str[1]){
          console.log(str[0]+str[1]);
          return;
     }
     for(let i=1;i<n;i++){
          if(str[i]<=p){
               p = str[i];
               k++;
          }
          else break;
     }
     let res = str.slice(0,k);
     let r = res+"";
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);

}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

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

// const lines = `4
// 10
// codeforces
// 9
// cbacbacba
// 3
// aaa
// 4
// bbaa
// 3
// ba
// 1
// zaa
// 2
// zbaaaa
// 1
// cbbba`.split("\n");

const solveProblem = (lines) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";

  const strings = lines.slice(2).filter((_, i) => i % 2 === 0);

  const results = [];

  for (let i = 0; i < strings.length; i++) {
    let firstOfCurrentChar = 0;
    let lastAlphabetIndex = Infinity;
    let sliceTo = 0;
    for (let j = 0; j < strings[i].length; j++) {
      const char = strings[i][j];
      const alphabetPosition = alphabet.indexOf(char);
      if (alphabetPosition < lastAlphabetIndex) {
        lastAlphabetIndex = alphabetPosition;
        firstOfCurrentChar = j;
        sliceTo = j + 1;
      } else if (
        alphabetPosition === lastAlphabetIndex &&
        firstOfCurrentChar !== 0
      ) {
        const mirrorPosition = firstOfCurrentChar - (j - firstOfCurrentChar);
        if (mirrorPosition < 0) {
          sliceTo = j + 1;
          continue;
        }
        const mirrorCharAlphabetPosition = alphabet.indexOf(
          strings[i][mirrorPosition]
        );
        if (mirrorCharAlphabetPosition > alphabetPosition) {
          sliceTo = j + 1;
          continue;
        }
        break;
      } else {
        break;
      }
    }
    const part1 = strings[i].slice(0, sliceTo);
    const part2 = part1.slice(0).split("").reverse().join("");
    results.push(part1 + part2);
  }

  console.log(results.join("\n"));
};

// solveProblem(lines);

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

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;

	let t = inputReader.readNumber();

	function solve() {
	  let n = inputReader.readNumber();
	  let s = inputReader.readLine();
	  let pos = n - 1;
	  for (let i = 0; i < n - 1; i++) {
	    if (s[i] < s[i + 1]) {
	      pos = i;
	      break;
	    }
	    if (s[i] == s[i + 1]) {
	      if (i == 0) {
	        pos = i;
	        break;
	      }
	    }
	  }
	  let ans = s.slice(0, pos + 1);
	  ans = ans.concat(ans.split("").reverse().join(""));
	  console.log(ans);
	}

	while (t--) {
	  solve();
	}

}

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 readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readLine(){
		return _inputLines[_lineNumber++];
	}

	return {
		readNumber,
		readLine,
	}
}

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

function reverse(s) {
   return s.split('').reverse().join('');
}
let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const s = await getLine();
        if (s.length === 1) {
            console.log(`${s}${s}`);
            continue;
        }
        if (s.charCodeAt(0) === s.charCodeAt(1)) {
            console.log(s.substr(0, 2));
            continue;
        }
        let i = 1
        while (i < s.length && s.charCodeAt(i) <= s.charCodeAt(i-1)) i++;
        console.log(`${s.substr(0, i)}${reverse(s.substr(0,i))}`);
    }
}

solve();

var t = parseInt(readline());
  function solve() {
    var n = parseInt(readline());
    var p = readline();
    var str1 = p[0];
    var str2 = p[0];
    var flag = false;
    for (var i = 1; i < n; i++) {
      if (p[i] < p[i - 1]) {
        str1 += p[i];
        str2 = p[i] + str2;
        flag = true;
      } else if (p[i] === p[i - 1]) {
        if (flag) {
          str1 += p[i];
          str2 = p[i] + str2;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    return str1 + str2;
  }

  while (t--) {
    print(solve());
  }

const solve = (n,str)=>{
     if(n===1) {
          console.log(str+str);
          return;
     }
     if(str[0]<str[1]){
          console.log(str[0]+str[0]);
          return;
     }
     else if(str[0]===str[1]){
          console.log(str[0]+str[1]);
          return;
     }
     let k = 0;
     for(let i=0;i<n;i++){
          if(str[k]>str[i]) k = i;
          if(str[k]===str[k+1]) k=k+1;
     }
     let res = str.slice(0,k+1);
     let r = res+"";
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);

}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

const solve = (n,str)=>{
     if(n===1) {
          console.log(str+str);
          return;
     }
     if(str[0]<=str[1]){
          console.log(str[0]+str[1]);
          return;
     }
     let k = 0;
     for(let i=0;i<n;i++){
          if(str[k]>str[i]) k = i;
          if(str[k]===str[k+1]) k=k+1;
     }
     let res = str.slice(0,k+1);
     let r = res+"";
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);

}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

const solve = (n,str)=>{
     if(n===1) {
          console.log(str+str);
          return;
     }
     if(str[0]===str[1]){
          console.log(str[0]+str[1]);
          return;
     }
     let k = 0;
     for(let i=0;i<n;i++){
          if(str[k]>str[i]) k = i;
          if(str[k]===str[k+1]) k=k+1;
     }
     let res = str.slice(0,k+1);
     let r = res+"";
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);

}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

const solve = (n,str)=>{
     if(n===1) {
          console.log(str+str);
          return;
     }
     let res = "";
     for(let i=0;i<n;i++){
          res+=str[i];
          if(i===n-1) break;
          if(str[i]===str[i+1]){
               if(i===0) break;
               i++;
               while((str[i-1]===str[i])&&(i<n)) res+=str[i++];
               break;
          }
          else if(str[i]<str[i+1]) break;
     }
     let r = ""+res;
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);
}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

const solve = (n,str)=>{
     if(n===1) {
          console.log(str+str);
          return;
     }
     let res = "";
     for(let i=0;i<n;i++){
          res+=str[i];
          if(i!==n-1) if(str[i]<=str[i+1]) break;
     }
     let r = ""+res;
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);
}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

const solve = (n,str)=>{
     if(n===1) {
          console.log(str+str);
          return;
     }
     let res = "";
     for(let i=0;i<n-1;i++){
          res+=str[i];
          if(str[i]<=str[i+1]) break;
     }
     let r = ""+res;
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);
}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

const solve = (n,str)=>{
     let res = "";
     for(let i=0;i<n-1;i++){
          res+=str[i];
          if(str[i]<=str[i+1]) break;
     }
     let r = ""+res;
     for(let i=res.length-1;i>=0;i--) r+=res[i];
     console.log(r);
}
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 n = parseInt(readline());
       let str = readline();
       solve(n,str);
  }
}
main();

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

// const lines = `4
// 10
// codeforces
// 9
// cbacbacba
// 3
// aaa
// 4
// bbaa
// 3
// ba
// 1
// zaa
// 2
// zbaaaa`.split("\n");

const solveProblem = (lines) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";

  const strings = lines.slice(2).filter((_, i) => i % 2 === 0);

  const results = [];

  for (let i = 0; i < strings.length; i++) {
    let firstOfCurrentChar = 0;
    let lastAlphabetIndex = Infinity;
    let sliceTo = 0;
    for (let j = 0; j < strings[i].length; j++) {
      const char = strings[i][j];
      const alphabetPosition = alphabet.indexOf(char);
      if (alphabetPosition < lastAlphabetIndex) {
        lastAlphabetIndex = alphabetPosition;
        firstOfCurrentChar = j;
        sliceTo = j + 1;
      } else if (alphabetPosition === lastAlphabetIndex) {
        const mirrorPosition = firstOfCurrentChar - (j - firstOfCurrentChar);
        if (mirrorPosition < 0) {
          break;
        }
        const mirrorCharAlphabetPosition = alphabet.indexOf(
          strings[i][mirrorPosition]
        );
        if (mirrorCharAlphabetPosition > alphabetPosition) {
          sliceTo = j + 1;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    const part1 = strings[i].slice(0, sliceTo);
    const part2 = part1.slice(0).split("").reverse().join("");
    results.push(part1 + part2);
  }

  console.log(results.join("\n"));
};

// solveProblem(lines);

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

// const lines = `4
// 10
// codeforces
// 9
// cbacbacba
// 3
// aaa
// 4
// bbaa
// 3
// ba`.split("\n");

const solveProblem = (lines) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";

  const strings = lines.slice(2).filter((_, i) => i % 2 === 0);

  const results = [];

  for (let i = 0; i < strings.length; i++) {
    let lastIndex = Infinity;
    let sliceTo = 0;
    for (let j = 0; j < strings[i].length; j++) {
      const char = strings[i][j];
      const alphabetPosition = alphabet.indexOf(char);
      if (alphabetPosition < lastIndex) {
        lastIndex = alphabetPosition;
        sliceTo = j + 1;
      } else {
        break;
      }
    }
    const part1 = strings[i].slice(0, sliceTo);
    const part2 = part1.slice(0).split("").reverse().join("");
    results.push(part1 + part2);
  }

  console.log(results.join("\n"));
};

// solveProblem(lines);

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

// const lines = `4
// 10
// codeforces
// 9
// cbacbacba
// 3
// aaa
// 4
// bbaa
// 3
// ba`.split("\n");

const solveProblem = (lines) => {
  const alphabet = "abcdefghijklmnopqrstuvwxyz";

  const strings = lines.slice(2).filter((_, i) => i % 2 === 0);

  const results = [];

  for (let i = 0; i < strings.length; i++) {
    let lastIndex = Infinity;
    for (let j = 0; j < strings[i].length; j++) {
      const char = strings[i][j];
      const alphabetPosition = alphabet.indexOf(char);
      if (alphabetPosition < lastIndex) {
        lastIndex = alphabetPosition;
      } else {
        const part1 = strings[i].slice(0, j);
        const part2 = part1.slice(0).split("").reverse().join("");
        results.push(part1 + part2);
        break;
      }
    }
  }

  console.log(results.join("\n"));
};

// solveProblem(lines);

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

function _main() {
  _inputLines = _inputData
    .trim()
    .split("\n")
    .map((string) => {
      return string.trim();
    });

  let t = inputReader.readNumber();

  function solve() {
    let n = inputReader.readNumber();
    let s = inputReader.readLine();
    let pos = n - 1;
    for (let i = 0; i < n - 1; i++) {
      if (s[i] <= s[i + 1]) {
        pos = i;
        break;
      }
    }
    let ans = s.slice(0, pos + 1);
    ans = ans.concat(ans.split("").reverse().join(""));
    console.log(ans);
  }

  while (t--) {
    solve();
  }
}

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 readNumber() {
    return Number(_inputLines[_lineNumber++]);
  }

  function readLine() {
    return _inputLines[_lineNumber++];
  }

  return {
    readNumber,
    readLine,
  };
}

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

function reverse(s) {
   return s.split('').reverse().join('');
}
let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const s = await getLine();
        if (s.length === 1) {
            console.log(s);
            continue;
        }
        if (s.charCodeAt(0) === s.charCodeAt(1)) {
            console.log(s.substr(0, 2));
            continue;
        }
        let i = 1
        while (i < s.length && s.charCodeAt(i) <= s.charCodeAt(i-1)) i++;
        console.log(`${s.substr(0, i)}${reverse(s.substr(0,i))}`);
    }
}

solve();

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

function reverse(s) {
   return s.split('').reverse().join('');
}
let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const s = await getLine();
        if (s.length === 1) {
            console.log(s);
            continue;
        }
        if (s.charCodeAt(0) === s.charCodeAt(1)) {
            console.log(s.substr(0, 2));
            continue;
        }
        let i = 1;
        while (i < s.length && s.charCodeAt(i) <= s.charCodeAt(i-1)) i++;
        if (i >= s.length) {
            console.log(s);
        } else {
            console.log(`${s.substr(0, i)}${reverse(s.substr(0,i))}`);
        }
    }
}

solve();

var t = parseInt(readline());

  function solve() {
    var n = parseInt(readline());
    var p = readline()
    var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    var str1 = p[0]
    var str2 = p[0]
    for (var i = 1; i < n; i++) {
      var index = arr.indexOf(str1[i - 1])
      if (p[i] === arr[index - 1]) {
        str1 += p[i]
        str2 = p[i] + str2
      } else {
        break;
      }
    }
    return str1 + str2;
  }

  while (t--) {
    print(solve())
  }


Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.

The first line contains an integer n (1 ≤ n ≤ 1000).

On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.

var n=+readline();
var a=[];

var f=true;
for(var i=0;i<n;i++){
	var k=a[i]=[];
	f=!f;
	if(f){
		for(var j=0;j<n;j++){
			k.push(j%2?'C':'.');
		}
	}else{
		for(var j=0;j<n;j++){
			k.push(j%2?'.':'C');
		}
	}

}
print(Math.ceil((n*n)/2));
for(var i=0;i<n;i++){
	print(a[i].join(''))
}

var n = +readline();
var ans;

if(n % 2 == 0){
	ans = n/2 * n;
}
else{
	ans = Math.ceil(n/2) * Math.ceil(n/2) + Math.floor(n/2) * Math.floor(n/2);
}

print(ans);

for(var i = 1; i <= n; i++){
	if(i % 2 == 1){
		for(j = 1; j <= n; j++){
			if(j % 2 == 1){
				write("C");
			}
			else{
				write(".");
			}
		}
		write("\n");
	}
	else{
		for(j = 1; j <= n; j++){
			if(j % 2 == 1){
				write(".");
			}
			else{
				write("C");
			}
		}
		write("\n");
	}
}

;(function () {

	var n = +readline();

	print(Math.ceil(n*n / 2));

	var str;
	for (var i = 0; i < n; i++) {
		str = '';
		for (var j = 0; j < n; j++) {
			str += ((i+j)%2) ? '.' : 'C';
		}
		print(str);
	}

}).call(this);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0];
	print(Math.floor((n*n+1)/2));
	for (var r = 0; r < n; r += 1) {
		var row = [];
		for (var c = 0; c < n; c += 1) {
			row.push((r+c)%2 == 0 ? 'C' : '.');
		}
		print(row.join(''));
	}
}

main();

var n = Number(readline());

var grid = new Array(n);
for (var i = 0; i < n; ++i)
    grid[i] = new Array(n)

var ans = 0;

for (var i = 0; i < n; ++i)
    for (var j = 0; j < n; ++j) {
        grid[i][j] = ((i + j) % 2 === 0) ? 'C' : '.';
        if (grid[i][j] == 'C')
            ++ans;
    }

print(ans);
grid.forEach(function(s) { print(s.join("")); });

var input = readline().split(' ');
var n = parseInt(input);
var sum=0;
if(n%2) for(var i=1; i<=n; i++)
{
sum+=Math.floor(n/2)+i%2;
}
else sum = (n/2)*n;
var answer = '';
answer+=sum+'\n';
for(var j=1; j<=n; j++){
for(var i=1; i<=n; i++)
{
if(i%2)
{
if(j%2)answer+='C';
else answer+='.';
}
else
{
if(j%2) answer+='.';
else answer+='C';
}
}
answer+='\n';
}
print(answer);

// 384A     Кодер

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);

var out = '';
var count = 0;

for (var i = 1; i <= n; i += 2) {
    if ((n % 2) !== 0) {
        count += Math.floor(n / 2) + 1;
        for (var j = 1; j < n/2; j++) out += 'C.';
        out += 'C\n';
        if (i < n) {
            count += Math.floor(n / 2);
            for (var j = 1; j < n/2; j++) out += '.C';
            out += '.\n';
        };
    } else {
        count += n;
        for (var j = 0; j < n/2; j++) out += 'C.';
        out += '\n';
        for (var j = 0; j < n/2; j++) out += '.C';
        out += '\n';
    };
};

print(count);
print(out);

var number = parseInt(readline());
var fs = "";
var sc = 0;

for (var i= 0 ; i<number ; i++){
    for(var j = 0; j<number ; j++){
   if(i % 2 === 0){
    if(j%2 === 0){
        fs+="C";
        sc++;
    }else{
        fs+=".";
    }
   }else {
    if(j%2 === 0){
      fs +=".";
    }else{
        fs+="C";
        sc++;
    }
   }

    }

    fs += "\n";
}
write(sc);
write("\n");
write(fs);

(function() {
    var i , n = parseInt(readline());
    var even = "", odd = "";
    for ( i = 0 ; i < n ; ++i){
        if ( i % 2 == 0 ){
            even += 'C';
            odd += '.'
        }else{
            even += '.';
            odd += 'C';
        }
    }
    print(Math.ceil((n*n)/2));
    for ( i = 0 ; i < n ; ++i){
        if ( i % 2 == 0 ){
            print(even);
        }else{
            print(odd);
        }
    }
})();

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

rl.on('line', (d) => {
  const board = new Array(+d).fill('.').map(x => new Array(+d).fill('.'));
  let pieces = 0;

  for (let i = 0; i < board.length; i++) {
    for (let j = 0; j < board[i].length; j++) {
      if (i % 2 === 0 && j % 2 === 0) {
        board[i][j] = 'C';
        pieces++;
      }
      else if (i % 2 !== 0 && j % 2 !== 0) {
        board[i][j] = 'C';
        pieces++;
      }
    }
  }

  console.log(pieces);
  for (let i = 0; i < board.length; i++) {
    console.log(board[i].join(''));
  }
});

;(function () {

	var n = +readline();

	print(Math.ceil(n*n / 2));

	var str;
	for (var i = 0; i < n; i++) {
		str = '';
		for (var j = 0; j < n; j++) {
			str += ((i+j)%2) ? 'C' : '.';
		}
		print(str);
	}

}).call(this);

;(function () {

	var n = +readline();

	print(Math.floor(n*n / 2));

	var str;
	for (var i = 0; i < n; i++) {
		str = '';
		for (var j = 0; j < n; j++) {
			str += ((i+j)%2) ? 'C' : '.';
		}
		print(str);
	}

}).call(this);

;(function () {

	var n = +readline();

	print(Math.floor(n / 2));

	var str;
	for (var i = 0; i < n; i++) {
		str = '';
		for (var j = 0; j < n; j++) {
			str += ((i+j)%2) ? '.' : 'C';
		}
		print(str);
	}

}).call(this);

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

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

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

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

	var p = 6 - Math.max(a, b) + 1;

	if (p == 6) {
		print("1/1");
	}
	else if (p == 3) {
		print("1/2");
	}
	else if (p%2 == 0) {
		print((p/2)+"/3");
	}
	else {
		print(p+"/6");
	}
}

main();

var n = Number(readline());

var grid = new Array(n);
for (var i = 0; i < n; ++i)
    grid[i] = new Array(n)

var ans = 0;

for (var i = 0; i < n; ++i)
    for (var j = 0; j < n; ++j) {
        grid[i][j] = ((i + j) % 2 === 0) ? 'c' : '.';
        if (grid[i][j] == 'C')
            ++ans;
    }

print(ans);
grid.forEach(function(s) { print(s.join("")); });

var n = Number(readline());

var grid = new Array(n);
for (var i = 0; i < n; ++i)
    grid[i] = new Array(n)

var ans = 0;

for (var i = 0; i < n; ++i)
    for (var j = 0; j < n; ++j) {
        grid[i][j] = ((i + j) % 2 === 0) ? 'c' : '.';
        if (grid[i][j] == 'c')
            ++ans;
    }

print(ans);
grid.forEach(function(s) { print(s.join("")); });

var n = Number(readline());

var grid = new Array(n);
for (var i = 0; i < n; ++i)
    grid[i] = new Array(n)

var ans = 0;

for (var i = 0; i < n; ++i)
    for (var j = 0; j < n; ++j) {
        grid[i][j] = ((i + j) % 2 === 0) ? 'C' : '.';
        if (grid[i][j] == 'c')
            ++ans;
    }

print(ans);
grid.forEach(function(s) { print(s.join("")); });

// 384A     Кодер

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);

var out = '';
var count = 0;

for (var i = 1; i <= n; i += 2) {
    if ((n % 2) !== 0) {
        count += n / 2 + 1;
        for (var j = 0; j < n/2; j++) out += 'C.';
        out += 'C\n';
        if (i < n) {
            count += n / 2;
            for (var j = 0; j < n/2; j++) out += '.C';
            out += '\n';
        };
    } else {
        count += n;
        for (var j = 0; j < n/2; j++) out += 'C.';
        out += '\n';
        for (var j = 0; j < n/2; j++) out += '.C';
        out += '\n';
    };
};

print(count);
print(out);

// 384A     Кодер

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);

var out = '';
var count = 0;

for (var i = 1; i <= n; i += 2) {
    if ((n % 2) !== 0) {
        count += n / 2 + 1;
        for (var j = 0; j < n/2; J++) out += 'C.';
        out += 'C\n';
        if (i < n) {
            count += n / 2;
            for (var j = 0; j < n/2; J++) out += '.C';
            out += '\n';
        };
    }
};

print(count);
print(out);

// 384A     Кодер

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);

var out = '';
var count = 0;

for (var i = 1; i <= n; i += 2) {
    if ((n % 2) !== 0) {
        count += n / 2 + 1;
        for (var j = 1; j < n/2; j++) out += 'C.';
        out += 'C\n';
        if (i < n) {
            count += n / 2;
            for (var j = 1; j < n/2; j++) out += '.C';
            out += '\n';
        };
    } else {
        count += n;
        for (var j = 0; j < n/2; j++) out += 'C.';
        out += '\n';
        for (var j = 0; j < n/2; j++) out += '.C';
        out += '\n';
    };
};

print(count);
print(out);

// 384A     Кодер

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);

var out = '';
var count = 0;

for (var i = 1; i <= n; i += 2) {
    if ((n % 2) !== 0) {
        count += n / 2 + 1;
        for (var j = 0; j < n/2; j++) out += 'C.';
        out += 'C\n';
        if (i < n) {
            count += n / 2;
            for (var j = 0; j < n/2; j++) out += '.C';
            out += '\n';
        };
    } else {
        count += n;
        for (var j = 0; j < n/2; j++) out += 'C.';
        for (var j = 0; j < n/2; j++) out += '.C';
        out += '\n';
    };
};

print(count);
print(out);

var number = parseInt(readline());
var fs = "";
var sc = 0;

for (var i= 0 ; i<number ; i++){
    for(var j = 0; j<number ; j++){
   if(i % 2 === 0){
    if(j%2 === 0){
        fs+="c";
        sc++;
    }else{
        fs+=".";
    }
   }else {
    if(j%2 === 0){
      fs +=".";
    }else{
        fs+="c";
        sc++;
    }
   }

    }

    fs += "\n";
}
write(sc);
write(fs);

var number = parseInt(readline());
var fs = "";
var sc = 0;

for (var i= 0 ; i<number ; i++){
    for(var j = 0; j<number ; j++){
   if(i % 2 === 0){
    if(j%2 === 0){
        fs+="c";
        sc++;
    }else{
        fs+=".";
    }
   }else {
    if(j%2 === 0){
      fs +=".";
    }else{
        fs+="c";
        sc++;
    }
   }

    }

    fs += "\n";
}
write(sc);
write("\n");
write(fs);

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

rl.on('line', (d) => {
  const board = new Array(+d).fill('.').map(x => new Array(+d).fill('.'));
  let pieces = 0;

  for (let i = 0; i < board.length; i++) {
    for (let j = 0; j < board[i].length; j++) {
      if (j % 2 === 0) {
        board[i][j] = 'C';
        pieces++;
      }
    }
  }

  console.log(pieces);
  for (let i = 0; i < board.length; i++) {
    console.log(board[i].join(''));
  }
});


You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).

"use strict";

(() => {

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

    let curLine = 0, allLines = [];

    let nextLine = () => {
        if(curLine == allLines.length) throw new ReferenceError("No more input in the buffer");
        return allLines[curLine++]
    };

    readline.on("line", line => { allLines.push(line); });
    readline.on("close", () => { main(nextLine) });

})();

function main(nextLine) {
    let t = Number(nextLine());

    while(t--) {
        let n = Number(nextLine());

        let vec = [];
        for(let i = 1; i <= n; i++) vec[i] = [];

        for(let i = 1; i <= n; i++) {
            let tmp = nextLine().split(" ").map(x => Number(x));
            let u = tmp[0], v = tmp[1];

            vec[u].push(v);
            vec[v].push(u);
        }

        let cycle = [];
        let col = new Array(n+1).fill(0), par = [];

        let dfs1 = s => {
            let st = [[s, 0]];

            while(st.length) {
                let tmp = st.pop();
                let u = tmp[0], i = tmp[1];

                if(i == 0) col[u] = 1;

                if(i < vec[u].length) st.push([u, i+1]);
                else {
                    col[u] = 2;
                    continue;
                }

                let v = vec[u][i];

                if(col[v] === 1 && par[u] !== v) {
                    let cur = u;

                    while(true) {
                        cycle.push(cur);
                        if(cur === v) break;

                        cur = par[cur];
                    }
                }

                if(col[v] === 0) {
                    par[v] = u;
                    st.push([v, 0]);
                }
            }
        };

        dfs1(1);

        col.fill(0);
        cycle.forEach(s => { col[s] = 1; });

        let ans = n*(n-1);

        let tot;
        let dfs2 = s => {
            let st = [[s, 0]];

            while(st.length) {
                let tmp = st.pop();
                let u = tmp[0], i = tmp[1];

                if(i == 0) col[u] = 1, tot++;

                if(i < vec[u].length) st.push([u, i+1]);
                else continue;

                let v = vec[u][i];
                if(col[v] == 0) st.push([v, 0]);
            }
        };

        cycle.forEach(s => {
            tot = 0;
            dfs2(s);

            ans -= tot*(tot-1)/2;
        });

        console.log(ans);
    }
}