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

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

  if (c % 2 === 1) {
    [n, k] = d.split(' ').map(Number);
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  let ans = min + k;

  if (min +  k < max - k) {
    ans = - 1;
  }

  console.log(ans);

  c++;
});

"use strict";

var q = +readline()

while (q--) {
    var input = readline().split(' ').map(value => +value);
    var n = input[0];
    var k = input[1];
    var A = readline().split(' ').map(value => +value);

    A.sort(function(a, b) {return a - b;});
    var result = A[0] + k;
    if (result < (A[n-1] - k)) {
        write('-1\n');
    } else {
        write(result + '\n');
    }
}

var qs = readline().split(' ').map(Number);

for (var i = 0; i < qs; i++) {
  var _ = readline().split(' ').map(Number);
  var n = _[0];
  var k = _[1];

  var goods = readline().split(' ').map(Number);

  var max = maxEl(goods);
  var min = minEl(goods);

  if (min + k >= max - k) {
    print(min + k);
  } else {
    print(-1);
  }
}

function minEl(arr) {
  var min = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
      min = arr[i];
    }
  }

  return min;
}

function maxEl(arr) {
  var max = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
  }

  return max;
}

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    };

    var q = read.number();
    var res = '';
    while (q) {
        q--;

        var line = read.arrNumber(' ');
        var n = line[0];
        var k = line[1];
        var a = read.arrNumber(' ');

        var max = a[0], min = a[0];
        for (var i = 0; i < n; i++) {
            if (max < a[i]) {
                max = a[i];
            }
            if (min > a[i]) {
                min = a[i];
            }
        }

        if ((max - min) > 2 * k) {
            res += '-1\n';
        } else {
            res += (min + k) + '\n';
        }

    }
    print(res);

}());

let input = "";
const { EOL } = require("os");
process.stdin.on("data", i => (input += i));

process.stdin.on("end", async () => {
  console.log(func(input));
});

const func = a => {
  let result = "";
  const [q, ...queries] = a.split(EOL);
  for (let i = 0; i < q; i++) {
    const [n, maxPriceDiff] = queries.shift().split(" ").map(a => parseInt(a));
    const products = queries
      .shift()
      .split(" ")
      .map(a => parseInt(a))
      .sort((a, b) => a - b);
    result +=
      (Math.abs(products[products.length - 1] - products[0]) <= maxPriceDiff * 2
        ? products[0] + maxPriceDiff
        : -1) + EOL;
  }
  return result;
};

module.exports = func;

var qs = readline().split(' ').map(Number);

for (var i = 0; i < qs; i++) {
  var _ = readline().split(' ').map(Number);
  var n = _[0];
  var k = _[1];

  var goods = readline().split(' ').map(Number);

  var sum = goods.reduce(function(prev, cur) {
    return prev + cur;
  });

  var avg = Math.ceil(sum / n);

  var max = maxEl(goods);
  var min = minEl(goods);

  if (avg - min > k || max - avg > k) {
    print(-1);
  } else if (avg - min < k)  {
    print(min + k);
  } else {
    print(avg);
  }
}

function minEl(arr) {
  var min = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
      min = arr[i];
    }
  }

  return min;
}

function maxEl(arr) {
  var max = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
  }

  return max;
}

"use strict";

var q = +readline()

while (q--) {
    var input = readline().split(' ').map(value => +value);
    var n = input[0];
    var k = input[1];
    var A = readline().split(' ').map(value => +value);

    A.sort();
    var result = A[0] + k;
    if (result < (A[n-1] - k)) {
        write('-1\n');
    } else {
        write(result + '\n');
    }
}


function kek(s)
{
    for (var i=0;i<=20;i++)
    {
        s=s.replace("u","oo")
        s=s.replace("kh","h");
    }
    return s;
}

var n=+readline()
var x=[]
while(n--)
{
    x.push(kek(readline()))
}
x.sort()
var res=1
for (var i=1;i<x.length;i++)
{
    if (x[i]!=x[i-1]){res++;}
}
print(res)//

function kek(s)
{
    s=s.replace("u","oo")
    for (var i=0;i<=20;i++)
    {
        s=s.replace("kh","h");
    }
    return s;
}

var n=+readline()
var x=[]
while(n--)
{
    x.push(kek(readline()))
}
x.sort()
var res=1
for (var i=1;i<x.length;i++)
{
    if (x[i]!=x[i-1]){res++;}
}
print(res)


const readline = require('readline');

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

rl.on('line', function (input) {
    var myArr = input.split(' ').map(item => { return parseFloat(item); });
    //****************************************** DO IT HERE*/
    var A = myArr[0], B = myArr[1];
    var N = parseInt(myArr[2]);
    var helper = 0;
    if(A==0 && B==0) helper = 0;
    else if (A==0 && B!=0) helper = -2;
    else helper = B/A;

    var needMinus = false;
    if(helper<0 && N%2)
    {
        needMinus = true;
        helper = -helper;
    }
    var ans = NthRoot(helper,N);
    if(ans>0)
    {
        ans+=0.0001;
        ans = Math.trunc(ans*1000);
        ans /=1000;
    }

    var temp = Math.trunc(ans);
    if(ans == temp)
        console.log(needMinus? "-" + ans : ans.toString());
    else
        console.log("No solution");

    rl.close();
    /*************************************** */

})

function NthRoot(Base, n) {
    return Math.pow(Base, 1.0 / n);
}

'use strict'

let lll = readline().split(' ').map(v => parseInt(v))

let bo = lll[0]
let bn = lll[1]
let n = lll[2]

let res = 'No solution'
;(function () {
  for (let i = -1000; i <= 1000; i++) {
    if (bo * Math.pow(i, n) == bn) return res = i
  }
})()

print(res)

const readline = require('readline');

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

rl.on('line', function (input) {
    var myArr = input.split(' ').map(item => { return parseFloat(item); });
    //****************************************** DO IT HERE*/
    var A = myArr[0], B = myArr[1];
    var N = parseInt(myArr[2]);
    var helper = 0;
    if(A==0 && B==0) helper = 0;
    else if (A==0 && B!=0) helper = -2;
    else helper = B/A;

    var needMinus = false;
    if(helper<0 && N%2)
    {
        needMinus = true;
        helper = -helper;
    }
    var ans = NthRoot(helper,N);
    if(ans>0)
    {
        ans+=0.0001;
        ans = Math.trunc(ans*1000);
        ans /=1000;
    }

    var temp = Math.trunc(ans);
    if(ans == temp)
        console.log(needMinus? "-" + ans : ans.toString());
    else
        console.log("No Solution");

    rl.close();
    /*************************************** */

})

function NthRoot(Base, n) {
    return Math.pow(Base, 1.0 / n);
}


const {EOL} = require('os');
let i = ''
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
  main(i);
})

function circularShift(str) {
  return str[str.length - 1] + str.slice(0, str.length - 1);
}

function getEqualityArray(shortString, longString) {
  let res = [], max = 0, len = 0;;
  for (let i = 0; i < shortString.length; i++) {
    if (shortString[i] === longString[i]) {
      if (shortString[i] === '$') {
        res.push('$');
        len = 0;
      } else {
        res.push(1);
        len++;
      }
    } else {
      res.push(0);
      len = 0;
    }
    if (len > max) max = len;
  }
  return {arr: res, max: max};
}

function getLcsLength(str1, str2) {
  if (str1 === str2) return str1.length;
  let shortString, longString;
  if (str1.length <= str2.length) {
    shortString = str1 + '$';
    longString = str2 + '$';
  } else {
    shortString = str2 + '$';
    longString = str1 + '$';
  }
  let maxLCSLength = 0;
  let longStringCopy = longString;

  for (let i = 0; i < longStringCopy.length; i++) {
    let ea = getEqualityArray(shortString, longStringCopy);
    if (ea.max > maxLCSLength) maxLCSLength = ea.max;
    longStringCopy = circularShift(longStringCopy);
  }

  return maxLCSLength;
}

function findMinChanges(a, b) {
  const lcs = getLcsLength(a, b);
  return a.length + b.length - 2 * lcs
}

function main (input) {
  let index = 0;
  const lines = input.split(EOL);

  const t = lines[index++];

  for (let i = 0; i < t; i++) {
    let a = lines[index++];
    let b = lines[index++];
    console.log(findMinChanges(a, b));
  }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let s1 = readline().trim().split("");
    let s2 = readline().trim().split("");
    if (s1.length < s2.length) [s1, s2] = [s2, s1];
    let cnt = 0;
    for (let i = 0; i < s1.length; i++) {
      let k = i;
      for (let j = 0; j < s2.length; j++) {
        let s = j,
          k = i,
          tp = 0;
        while (k < s1.length && s1[k] === s2[s]) {
          tp++;
          k++;
          s++;
        }
        cnt = Math.max(cnt, tp);
      }
    }
    if (cnt === s1.length && cnt === s2.length) console.log(0);
    else console.log(s1.length + s2.length - cnt * 2);
  }
};
solve();

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
///////////////////////////////////////////////////////////////////////////////////

const solve = (a, b) => {
    let res = LongestCommonSubstringLen(a, b);
    pr(a.length + b.length - res * 2);
};

const LongestCommonSubstringLen = (A, B) => {
    let m = A.length;
    let n = B.length;
    let maxLen = 0;
    let dp = initialize2DArrayNew(m + 1, n + 1);
    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            if (A[i - 1] == B[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
                if (dp[i][j] > maxLen) {
                    maxLen = dp[i][j];
                }
            }
        }
    }
    return maxLen;
};

const initialize2DArrayNew = (m, n) => {
    let data = [];
    for (let i = 0; i < m; i++) {
        let tmp = new Array(n).fill(0);
        data.push(tmp);
    }
    return data;
};

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

main()

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
const mx = Math.max;
///////////////////////////////////////////////////////////////////////////////////

const solve = (a, b) => {
    let res = LongestCommonSubstring(a, b).length;
    pr(a.length + b.length - res * 2);
};

const LongestCommonSubstring = (A, B) => {
    let m = A.length;
    let n = B.length;
    let maxLen = 0;
    let endIdx = m;
    let dp = initialize2DArrayNew(m + 1, n + 1);
    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            if (A[i - 1] == B[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
                if (dp[i][j] > maxLen) {
                    maxLen = dp[i][j];
                    endIdx = i;
                }
            }
        }
    }
    return A.slice(endIdx - maxLen, endIdx);
};

const initialize2DArrayNew = (m, n) => {
    let data = [];
    for (let i = 0; i < m; i++) {
        let tmp = new Array(n).fill(0);
        data.push(tmp);
    }
    return data;
};

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

main()

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

let TC = 0;
let A, B;
readline.on('line', line => {
    if (TC === 0) {
        TC = Number(line.toString());
        return;
    }
    if (!A) {
        A = line.toString();
        return;
    }
    B = line.toString();
    if (A.length > B.length) {
        [B, A] = [A, B];
    }
    let maxMatchLength = 0;
    for (let i = 0; i < A.length; i++) {
        for (let j = 1; j < A.length - i + 1; j++) {
            const t = A.substr(i, j);
            if (B.indexOf(t) > -1) {
                const matchLength = t.length;
                if (maxMatchLength < matchLength) {
                    maxMatchLength = matchLength;
                }
            }
        }
    }
    console.log((A.length - maxMatchLength) + (B.length - maxMatchLength));

    A = undefined; B = undefined;
    TC--;
    if (TC === 0) {
        process.exit();
    }
});

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
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

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

// ********** Code Start **********
const getStringByLength = (strA, strB) => {
  const lenA = strA.length;
  const lenB = strB.length;

  if (lenA < lenB) return [strA, strB];

  return [strB, strA];
};
function main() {
  let num = parseInt(readline());
  while (num--) {
    let str1 = readline();
    let str2 = readline();
    const [strA, strB] = getStringByLength(str1, str2);
    let start = 0;
    let max = 0;
    for (let i = 0; i < strA.length; i++) {
      if (strB.includes(strA.substring(start, i + 1))) {
        max = Math.max(max, i - start + 1);
      } else start++;
    }
    print(strA.length - max + strB.length - max);
  }
}

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
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

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

// ********** Code Start **********
const getStringByLength = (strA, strB) => {
  const lenA = strA.length;
  const lenB = strB.length;

  if (lenA < lenB) return [strA, strB];

  return [strB, strA];
};
function main() {
  var num = parseInt(readline())
	while(num--){
    var str1 = readline()
    var str2 = readline()
    const [strA, strB] = getStringByLength(str1, str2)
    var start = 0
    var max = 0
    for(let i = 0; i < strA.length;i++){
      if(strB.includes(strA.substring(start, i + 1))){
        max = Math.max(max, i - start +1)
      }
      else start++
    }
    print(strA.length - max + strB.length - max)
  }
}

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

const getStringByLength = (strA, strB) => {
  const lenA = strA.length;
  const lenB = strB.length;

  if (lenA < lenB) return [strA, strB];

  return [strB, strA];
};

const main = () => {
  const rows = parseInt(readline());

  for (let idx = 0; idx < rows; idx++) {
    const wordA = readline();
    const wordB = readline();

    const [strA, strB] = getStringByLength(wordA, wordB);
    let startPos = 0;
    let maxLength = 0;
    for (let jdx = 0; jdx < strA.length; jdx++) {
      const wordSoFar = strA.substring(startPos, jdx + 1);
      if (strB.includes(wordSoFar)) {
        maxLength = Math.max(maxLength, jdx - startPos + 1);
      } else {
        startPos += 1;
      }
    }

    const answer = strA.length - maxLength + strB.length - maxLength;
    console.log(answer);
  }
};

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function solve() {
   var a = read();
   var b = read();
   var maxCommon = 0;
   for (var as = 0; as < a.length; as++) {
      for (var af = as + 1; af <= a.length; af++) {
         for (var bs = 0; bs < b.length; bs++) {
            for (var bf = bs + 1; bf <= b.length; bf++) {
               if (bf - bs !== af - as) {
                  continue;
               }
               if (a.substring(as, af) !== b.substring(bs, bf)) {
                  continue;
               }
               if (af - as > maxCommon) {
                  maxCommon = af - as;
               }
            }
         }
      }
   }
   write(a.length + b.length - maxCommon * 2);
}

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 {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      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 readAll() {
   return isNode && MEMORY;
}

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var n = Number(input[0]);
    var j = 1;
    for (let i = 1; i <= n; i++) {
        var str1 = input[j];
        j++;
        var str2 = input[j];
        j++;
        function minOperation(str1, str2) {
            var max = 0;
            for (var i = 0; i < str1.length; i++) {
                var str = "";
                for (var j = i; j < str1.length; j++) {
                    str += str1[j];
                    if (str2.indexOf(str) >= 0) {
                        max = Math.max(max, str.length);
                    }
                }
            }
            return (str1.length - max) + (str2.length - max);
        }
        console.log(minOperation(str1, str2));
    }
})

//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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	for(var i = 0; i < t; i++){
		var a = next();
		var b = next();
		var count = a.length + b.length;
		for(var j = 0; j < a.length; j++){
			for(var k = j; k < a.length; k++){
				var na = a.substring(j, k + 1);
				for(var l = 0; l < b.length; l++){
					for(var m = l; m < b.length; m++){
						var nb = b.substring(l, m + 1);
						if(na == nb){
							count = Math.min(count, (a.length - na.length) + (b.length - nb.length));
						}
					}
				}
			}
		}
		myout(count);
	}
}

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

// Make a Snippet for the code above this and then write your logic in main();
var mod = 998244353n
var maxN = 10e6 + 1

function main() {
  var x = parseInt(readline())
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {

    var a = readline()
    var b = readline()
    var string = longestCommonSubstring(a,b)

    // if(!string) return console.log(a.length + b.length)

    console.log(a.length + b.length - 2*string.length)
  })
}
function longestCommonSubstring(string1, string2) {
  // Convert strings to arrays to treat unicode symbols length correctly.
  // For example:
  // '𐌵'.length === 2
  // [...'𐌵'].length === 1
  const s1 = [...string1];
  const s2 = [...string2];

  // Init the matrix of all substring lengths to use Dynamic Programming approach.
  const substringMatrix = Array(s2.length + 1).fill(null).map(() => {
    return Array(s1.length + 1).fill(null);
  });

  // Fill the first row and first column with zeros to provide initial values.
  for (let columnIndex = 0; columnIndex <= s1.length; columnIndex += 1) {
    substringMatrix[0][columnIndex] = 0;
  }

  for (let rowIndex = 0; rowIndex <= s2.length; rowIndex += 1) {
    substringMatrix[rowIndex][0] = 0;
  }

  // Build the matrix of all substring lengths to use Dynamic Programming approach.
  let longestSubstringLength = 0;
  let longestSubstringColumn = 0;
  let longestSubstringRow = 0;

  for (let rowIndex = 1; rowIndex <= s2.length; rowIndex += 1) {
    for (let columnIndex = 1; columnIndex <= s1.length; columnIndex += 1) {
      if (s1[columnIndex - 1] === s2[rowIndex - 1]) {
        substringMatrix[rowIndex][columnIndex] = substringMatrix[rowIndex - 1][columnIndex - 1] + 1;
      } else {
        substringMatrix[rowIndex][columnIndex] = 0;
      }

      // Try to find the biggest length of all common substring lengths
      // and to memorize its last character position (indices)
      if (substringMatrix[rowIndex][columnIndex] > longestSubstringLength) {
        longestSubstringLength = substringMatrix[rowIndex][columnIndex];
        longestSubstringColumn = columnIndex;
        longestSubstringRow = rowIndex;
      }
    }
  }

  if (longestSubstringLength === 0) {
    // Longest common substring has not been found.
    return '';
  }

  // Detect the longest substring from the matrix.
  let longestSubstring = '';

  while (substringMatrix[longestSubstringRow][longestSubstringColumn] > 0) {
    longestSubstring = s1[longestSubstringColumn - 1] + longestSubstring;
    longestSubstringRow -= 1;
    longestSubstringColumn -= 1;
  }

  return longestSubstring;
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let s1 = readline().trim().split("");
    let s2 = readline().trim().split("");
    let cnt = 0;
    for (let i = 0; i < s1.length; i++) {
      let k = 0,
        l = i;
      for (let j = 0; j < s2.length; j++) {
        if (s2[j] === s1[l] && l < s1.length) {
          k++;
          l++;
        } else {
          cnt = Math.max(cnt, k);
          l = i;
          if (k !== 0) j--;
          k = 0;
        }
      }
      cnt = Math.max(cnt, k);
    }
    if (cnt === s1.length && cnt === s2.length) console.log(0);
    else console.log(s1.length + s2.length - cnt * 2);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let s1 = readline().trim().split("");
    let s2 = readline().trim().split("");
    let cnt = 0;
    for (let i = 0; i < s1.length; i++) {
      let k = 0,
        l = i;
      for (let j = 0; j < s2.length; j++) {
        if (s2[j] === s1[l] && l < s1.length) {
          k++;
          l++;
        } else {
          cnt = Math.max(cnt, k);
          l = i;
          k = 0;
        }
      }
      cnt = Math.max(cnt, k);
    }
    if (cnt === s1.length && cnt === s2.length) console.log(0);
    else console.log(s1.length + s2.length - cnt * 2);
  }
};
solve();

///////////////////////////////// pre-define /////////////////////////////////////
const pr = console.log;
const mx = Math.max;
///////////////////////////////////////////////////////////////////////////////////

const solve = (a, b) => {
    let an = a.length;
    let bn = b.length;
    an <= bn ? go(a, b) : go(b, a);
};

const go = (short, long) => {
    let sn = short.length;
    let ln = long.length;
    if (sn == ln && short == long) return pr(0);
    if (long.indexOf(short) != -1) return pr(sn);
    let res = 0;
    for (let i = 0; i < sn; i++) {
        for (let j = i; j < sn; j++) {
            let len = j - i + 1;
            let sub = short.slice(i, j + 1);
            if (long.indexOf(sub) != -1) {
                res = mx(res, len);
            }
        }
    }
    pr(sn + ln - res * 2);
}

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

main()

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

let TC = 0;
let A, B;
readline.on('line', line => {
    if (TC === 0) {
        TC = Number(line.toString());
        return;
    }
    if (!A) {
        A = line.toString();
        return;
    }
    B = line.toString();
    if (A.length > B.length) {
        [B, A] = [A, B];
    }
    let maxMatchLength = 0;
    for (let i = 0; i < A.length; i++) {
        for (let j = i + 1; j < A.length - i; j++) {
            const t = A.substr(i, j);
            if (B.indexOf(t) > -1) {
                const matchLength = t.length;
                if (maxMatchLength < matchLength) {
                    maxMatchLength = matchLength;
                }
            }
        }
    }
    console.log((A.length - maxMatchLength) + (B.length - maxMatchLength));

    A = undefined; B = undefined;
    TC--;
    if (TC === 0) {
        process.exit();
    }
});


function main(a, b) {
  // define variables
  var config = {
    sources: {
      insert: 0,
      remove: 1,
      matching: 2,
    },
    scores: {
      match: 0,
      replace: -1,
      insert: -1,
      remove: -1
    },
  };
  function create() {
    var table = [];
    for (var i = 0; i < a.length + 1; i++) {
      var row = [];
      for (var j = 0; j < b.length + 1; j++) {
        row.push(null);
      }
      table.push(row);
    }
    return table;
  }
  var scores = create();
  var sources = create();
  var letters = create();

  // compute first row and first column
  scores[0][0] = 0;
  for (var i = 0; i < a.length; i++) {
    scores[i + 1][0] = (i + 1) * config.scores.remove;
    sources[i + 1][0] = config.sources.remove;
    letters[i + 1][0] = a[i];
  }
  for (var i = 0; i < b.length; i++) {
    scores[0][i + 1] = (i + 1) * config.scores.insert;
    sources[0][i + 1] = config.sources.insert;
    letters[0][i + 1] = b[i];
  }

  // compute the whole table
  for (var i = 1; i < scores.length; i++) {
    for (var j = 1; j < scores[i].length; j++) {
      var match = a[i - 1] === b[j - 1];
      var insertScore = scores[i][j - 1] + config.scores.insert;
      var removeScore = scores[i - 1][j] + config.scores.remove;
      var matchingScore = scores[i - 1][j - 1] + config.scores[match ? 'match' : 'replace'];

      if (insertScore >= removeScore && insertScore >= matchingScore) {
        scores[i][j] = insertScore;
        sources[i][j] = config.sources.insert;
        letters[i][j] = b[j - 1];
      } else if (removeScore >= insertScore && removeScore >= matchingScore) {
        scores[i][j] = removeScore;
        sources[i][j] = config.sources.remove;
        letters[i][j] = a[i - 1];
      } else if (matchingScore >= removeScore && matchingScore >= insertScore) {
        scores[i][j] = matchingScore;
        sources[i][j] = config.sources.matching;
        letters[i][j] = match ? ' ' : b[j - 1];
      }
    }
  }

  // return the editing operation list
  var path = [];
  var j = b.length;
  var i = a.length;
  var current = a.slice();
  while (i > 0 || j > 0) {
    if (sources[i][j] === config.sources.matching) {
      if (scores[i][j] < scores[i - 1][j - 1]) {
        current[i - 1] = letters[i][j];
        path.push({
          current: current.slice(),
          type: 'replace',
          position: i,
          item: letters[i][j],
        });
      }
      i--;
      j--;
    } else if (sources[i][j] === config.sources.remove) {
      current.splice(i - 1, 1);
      path.push({
        current: current.slice(),
        type: 'delete',
        position: i,
        item: letters[i][j],
      });
      i--;
    } else if (sources[i][j] === config.sources.insert) {
      current.splice(i, 0, letters[i][j]);
      path.push({
        current: current.slice(),
        type: 'insert',
        position: i + 1,
        item: letters[i][j],
      });
      j--;
    }
  }
  return path;
}

var a = readline().trim();
var b = readline().trim();
var changes = main(a.split(''), b.split(''));

print(changes.length);
changes.forEach(function (change) {
  print(change.type.toUpperCase() + ' ' + change.position + (change.type === 'delete' ? '' : (' ' + change.item)));
});

function main(a, b) {
  // define variables
  var i, j;
  var config = {
    sources: {
      insert: 0,
      remove: 1,
      matching: 2
    },
    scores: {
      match: 0,
      replace: -1,
      insert: -1,
      remove: -1
    }
  };
  function create() {
    var table = [];
    for (var i = 0; i < a.length + 1; i++) {
      var row = [];
      for (var j = 0; j < b.length + 1; j++) {
        row.push(null);
      }
      table.push(row);
    }
    return table;
  }
  var scores = create();
  var sources = create();
  var letters = create();

  // compute first row and first column
  scores[0][0] = 0;
  for (i = 0; i < a.length; i++) {
    scores[i + 1][0] = (i + 1) * config.scores.remove;
    sources[i + 1][0] = config.sources.remove;
    letters[i + 1][0] = a[i];
  }
  for (i = 0; i < b.length; i++) {
    scores[0][i + 1] = (i + 1) * config.scores.insert;
    sources[0][i + 1] = config.sources.insert;
    letters[0][i + 1] = b[i];
  }

  // compute the whole table
  for (i = 1; i < scores.length; i++) {
    for (j = 1; j < scores[i].length; j++) {
      var match = a[i - 1] === b[j - 1];
      var insertScore = scores[i][j - 1] + config.scores.insert;
      var removeScore = scores[i - 1][j] + config.scores.remove;
      var matchingScore = scores[i - 1][j - 1] + config.scores[match ? 'match' : 'replace'];

      if (insertScore >= removeScore && insertScore >= matchingScore) {
        scores[i][j] = insertScore;
        sources[i][j] = config.sources.insert;
        letters[i][j] = b[j - 1];
      } else if (removeScore >= insertScore && removeScore >= matchingScore) {
        scores[i][j] = removeScore;
        sources[i][j] = config.sources.remove;
        letters[i][j] = a[i - 1];
      } else if (matchingScore >= removeScore && matchingScore >= insertScore) {
        scores[i][j] = matchingScore;
        sources[i][j] = config.sources.matching;
        letters[i][j] = match ? null : {
          from: a[i - 1],
          to: b[j - 1]
        };
      }
    }
  }

  // return the editing operation list
  var operations = [];
  j = b.length;
  i = a.length;
  while (i > 0 || j > 0) {
    if (sources[i][j] === config.sources.matching) {
      if (scores[i][j] < scores[i - 1][j - 1]) {
        operations.push({
          type: 'replace',
          position: i,
          item: letters[i][j]
        });
      }
      i--;
      j--;
    } else if (sources[i][j] === config.sources.remove) {
      operations.push({
        type: 'delete',
        position: i,
        item: letters[i][j]
      });
      i--;
    } else if (sources[i][j] === config.sources.insert) {
      operations.push({
        type: 'insert',
        position: i + 1,
        item: letters[i][j]
      });
      j--;
    }
  }

  return operations;
}

var a = readline().trim();
var b = readline().trim();
var changes = main(a.split(''), b.split(''));

print(changes.length);
changes.forEach(function (change) {
  print(change.type.toUpperCase() + ' ' + change.position + (change.type === 'delete' ? '' : (' ' + (change.type === 'replace' ? change.item.to : change.item))));
});

var debug = false;

function main(a, b) {
  if (debug) {
    print(a);
    print(b);
  }

  // define variables
  var config = {
    sources: {
      insert: 'li',
      remove: 'ur',
      matching: 'dm',
    },
    scores: {
      match: 0,
      replace: -1,
      insert: -1,
      remove: -1
    },
  };
  function create() {
    var table = [];
    for (var i = 0; i < a.length + 1; i++) {
      var row = [];
      for (var j = 0; j < b.length + 1; j++) {
        row.push(null);
      }
      table.push(row);
    }
    return table;
  }
  function show(table) {
    if (!debug) {
      return;
    }
    write('     ');
    for (var i = 0; i < table[0].length - 1; i++) {
      write(b[i] + '  ');
    }
    write('\n');

    for (var i = 0; i < table.length; i++) {
      if (i > 0) {
        write(a[i - 1] + ' ');
      } else {
        write('  ');
      }
      for (var j = 0; j < table[i].length; j++) {
        write(table[i][j] + ' ');
      }
      write('\n');
    }
  }
  var scores = create();
  var sources = create();
  var letters = create();

  show(scores);

  // compute first row and first column
  scores[0][0] = 0;
  for (var i = 0; i < a.length; i++) {
    scores[i + 1][0] = (i + 1) * config.scores.remove;
    sources[i + 1][0] = config.sources.remove;
    letters[i + 1][0] = a[i];
  }
  for (var i = 0; i < b.length; i++) {
    scores[0][i + 1] = (i + 1) * config.scores.insert;
    sources[0][i + 1] = config.sources.insert;
    letters[0][i + 1] = b[i];
  }

  show(scores);

  // compute the whole table
  for (var i = 1; i < scores.length; i++) {
    for (var j = 1; j < scores[i].length; j++) {
      var match = a[i - 1] === b[j - 1];
      var insertScore = scores[i][j - 1] + config.scores.insert;
      var removeScore = scores[i - 1][j] + config.scores.remove;
      var matchingScore = scores[i - 1][j - 1] + config.scores[match ? 'match' : 'replace'];

      if (insertScore >= removeScore && insertScore >= matchingScore) {
        scores[i][j] = insertScore;
        sources[i][j] = config.sources.insert;
        letters[i][j] = b[j - 1];
      } else if (removeScore >= insertScore && removeScore >= matchingScore) {
        scores[i][j] = removeScore;
        sources[i][j] = config.sources.remove;
        letters[i][j] = a[i - 1];
      } else if (matchingScore >= removeScore && matchingScore >= insertScore) {
        scores[i][j] = matchingScore;
        sources[i][j] = config.sources.matching;
        letters[i][j] = match ? ' ' : b[j - 1];
      }
    }
  }

  show(scores);
  show(sources);
  show(letters);

  var path = [];
  var j = b.length;
  var i = a.length;
  var current = a.slice();

  while (i > 0 || j > 0) {
    if (sources[i][j] === config.sources.matching) {
      if (scores[i][j] < scores[i - 1][j - 1]) {
        current[i - 1] = letters[i][j];
        path.push({
          current: current.slice(),
          type: 'replace',
          position: i,
          item: letters[i][j],
        });
      }
      i--;
      j--;
    } else if (sources[i][j] === config.sources.remove) {
      current.splice(i - 1, 1);
      path.push({
        current: current.slice(),
        type: 'delete',
        position: i,
        item: letters[i][j],
      });
      i--;
    } else if (sources[i][j] === config.sources.insert) {
      current.splice(i, 0, letters[i][j]);
      path.push({
        current: current.slice(),
        type: 'insert',
        position: i + 1,
        item: letters[i][j],
      });
      j--;
    }
  }

  return path;
}

var a = readline().trim();
var b = readline().trim();
/*
a = 'seven';
b = 'sved';
a = 'aba';
b = 'abbba';
a = 'accepted';
b = 'wronganswer';
*/
var changes = main(a.split(''), b.split(''));

if (debug) {
  print(a)
  print(b)
}
print(changes.length);
changes.forEach(function (change) {
  print(change.type.toUpperCase() + ' ' + change.position + (change.type === 'delete' ? '' : (' ' + change.item)));
  //print(change.type.toUpperCase() + ' ' + change.position + ' ' + change.item + ' (' + change.current.join('') + ')');
});

var debug = false;

function main(a, b) {
  if (debug) {
    print(a);
    print(b);
  }

  // define variables
  var config = {
    sources: {
      insert: 'li',
      remove: 'ur',
      matching: 'dm',
    },
    scores: {
      match: 0,
      replace: -1,
      insert: -1,
      remove: -1
    },
  };
  function create() {
    var table = [];
    for (var i = 0; i < a.length + 1; i++) {
      var row = [];
      for (var j = 0; j < b.length + 1; j++) {
        row.push(null);
      }
      table.push(row);
    }
    return table;
  }
  function show(table) {
    if (!debug) {
      return;
    }
    write('     ');
    for (var i = 0; i < table[0].length - 1; i++) {
      write(b[i] + '  ');
    }
    write('\n');

    for (var i = 0; i < table.length; i++) {
      if (i > 0) {
        write(a[i - 1] + ' ');
      } else {
        write('  ');
      }
      for (var j = 0; j < table[i].length; j++) {
        write(table[i][j] + ' ');
      }
      write('\n');
    }
  }
  var scores = create();
  var sources = create();
  var letters = create();

  show(scores);

  // compute first row and first column
  scores[0][0] = 0;
  for (var i = 0; i < a.length; i++) {
    scores[i + 1][0] = (i + 1) * config.scores.remove;
    sources[i + 1][0] = config.sources.remove;
    letters[i + 1][0] = a[i];
  }
  for (var i = 0; i < b.length; i++) {
    scores[0][i + 1] = (i + 1) * config.scores.insert;
    sources[0][i + 1] = config.sources.insert;
    letters[0][i + 1] = b[i];
  }

  show(scores);

  // compute the whole table
  for (var i = 1; i < scores.length; i++) {
    for (var j = 1; j < scores[i].length; j++) {
      var match = a[i - 1] === b[j - 1];
      var insertScore = scores[i][j - 1] + config.scores.insert;
      var removeScore = scores[i - 1][j] + config.scores.remove;
      var matchingScore = scores[i - 1][j - 1] + config.scores[match ? 'match' : 'replace'];

      if (insertScore >= removeScore && insertScore >= matchingScore) {
        scores[i][j] = insertScore;
        sources[i][j] = config.sources.insert;
        letters[i][j] = b[j - 1];
      } else if (removeScore >= insertScore && removeScore >= matchingScore) {
        scores[i][j] = removeScore;
        sources[i][j] = config.sources.remove;
        letters[i][j] = a[i - 1];
      } else if (matchingScore >= removeScore && matchingScore >= insertScore) {
        scores[i][j] = matchingScore;
        sources[i][j] = config.sources.matching;
        letters[i][j] = match ? ' ' : b[j - 1];
      }
    }
  }

  show(scores);
  show(sources);
  show(letters);

  var path = [];
  var j = b.length;
  var i = a.length;
  var current = a.slice();

  while (i > 0 || j > 0) {
    if (sources[i][j] === config.sources.matching) {
      if (scores[i][j] < scores[i - 1][j - 1]) {
        current[i - 1] = letters[i][j];
        path.push({
          current: current.slice(),
          type: 'replace',
          position: i,
          item: letters[i][j],
        });
      }
      i--;
      j--;
    } else if (sources[i][j] === config.sources.remove) {
      current.splice(i - 1, 1);
      path.push({
        current: current.slice(),
        type: 'remove',
        position: i,
        item: letters[i][j],
      });
      i--;
    } else if (sources[i][j] === config.sources.insert) {
      current.splice(i, 0, letters[i][j]);
      path.push({
        current: current.slice(),
        type: 'insert',
        position: i + 1,
        item: letters[i][j],
      });
      j--;
    }
  }

  return path;
}

var a = readline().trim();
var b = readline().trim();
/*
a = 'seven';
b = 'sved';
a = 'aba';
b = 'abbba';
a = 'accepted';
b = 'wronganswer';
*/
var changes = main(a.split(''), b.split(''));

if (debug) {
  print(a)
  print(b)
}
print(changes.length);
changes.forEach(function (change) {
  print(change.type.toUpperCase() + ' ' + change.position + ' ' + change.item);
  //print(change.type.toUpperCase() + ' ' + change.position + ' ' + change.item + ' (' + change.current.join('') + ')');
});

var debug = false;

function main(a, b) {
  if (debug) {
    print(a);
    print(b);
  }

  // define variables
  var config = {
    sources: {
      insert: 'li',
      remove: 'ur',
      matching: 'dm',
    },
    scores: {
      match: 0,
      replace: -1,
      insert: -1,
      remove: -1
    },
  };
  function create() {
    var table = [];
    for (var i = 0; i < a.length + 1; i++) {
      var row = [];
      for (var j = 0; j < b.length + 1; j++) {
        row.push(null);
      }
      table.push(row);
    }
    return table;
  }
  function show(table) {
    if (!debug) {
      return;
    }
    write('     ');
    for (var i = 0; i < table[0].length - 1; i++) {
      write(b[i] + '  ');
    }
    write('\n');

    for (var i = 0; i < table.length; i++) {
      if (i > 0) {
        write(a[i - 1] + ' ');
      } else {
        write('  ');
      }
      for (var j = 0; j < table[i].length; j++) {
        write(table[i][j] + ' ');
      }
      write('\n');
    }
  }
  var scores = create();
  var sources = create();
  var letters = create();

  show(scores);

  // compute first row and first column
  scores[0][0] = 0;
  for (var i = 0; i < a.length; i++) {
    scores[i + 1][0] = (i + 1) * config.scores.remove;
    sources[i + 1][0] = config.sources.remove;
    letters[i + 1][0] = a[i];
  }
  for (var i = 0; i < b.length; i++) {
    scores[0][i + 1] = (i + 1) * config.scores.insert;
    sources[0][i + 1] = config.sources.insert;
    letters[0][i + 1] = b[i];
  }

  show(scores);

  // compute the whole table
  for (var i = 1; i < scores.length; i++) {
    for (var j = 1; j < scores[i].length; j++) {
      var match = a[i - 1] === b[j - 1];
      var insertScore = scores[i][j - 1] + config.scores.insert;
      var removeScore = scores[i - 1][j] + config.scores.remove;
      var matchingScore = scores[i - 1][j - 1] + config.scores[match ? 'match' : 'replace'];

      if (insertScore >= removeScore && insertScore >= matchingScore) {
        scores[i][j] = insertScore;
        sources[i][j] = config.sources.insert;
        letters[i][j] = b[j - 1];
      } else if (removeScore >= insertScore && removeScore >= matchingScore) {
        scores[i][j] = removeScore;
        sources[i][j] = config.sources.remove;
        letters[i][j] = a[i - 1];
      } else if (matchingScore >= removeScore && matchingScore >= insertScore) {
        scores[i][j] = matchingScore;
        sources[i][j] = config.sources.matching;
        letters[i][j] = match ? ' ' : b[j - 1];
      }
    }
  }

  show(scores);
  show(sources);
  show(letters);

  var path = [];
  var j = b.length;
  var i = a.length;
  var current = a.slice();

  while (i > 0 || j > 0) {
    if (sources[i][j] === config.sources.matching) {
      if (scores[i][j] < scores[i - 1][j - 1]) {
        current[i - 1] = letters[i][j];
        path.push({
          current: current.slice(),
          type: 'replace',
          position: i,
          item: letters[i][j],
        });
      }
      i--;
      j--;
    } else if (sources[i][j] === config.sources.remove) {
      current.splice(i - 1, 1);
      path.push({
        current: current.slice(),
        type: 'delete',
        position: i,
        item: letters[i][j],
      });
      i--;
    } else if (sources[i][j] === config.sources.insert) {
      current.splice(i, 0, letters[i][j]);
      path.push({
        current: current.slice(),
        type: 'insert',
        position: i + 1,
        item: letters[i][j],
      });
      j--;
    }
  }

  return path;
}

var a = readline().trim();
var b = readline().trim();
/*
a = 'seven';
b = 'sved';
a = 'aba';
b = 'abbba';
a = 'accepted';
b = 'wronganswer';
*/
var changes = main(a.split(''), b.split(''));

if (debug) {
  print(a)
  print(b)
}
print(changes.length);
changes.forEach(function (change) {
  print(change.type.toUpperCase() + ' ' + change.position + ' ' + change.item);
  //print(change.type.toUpperCase() + ' ' + change.position + ' ' + change.item + ' (' + change.current.join('') + ')');
});


var p = readline().split(/\s/gi).map(Number),
			q = p[1], l = p[2], r = p[3], p = p[0],
			abArr = [ [ -1, -1 ] ], cdArr = [ [ -1, -1 ] ], result = {};

		for(var i = 1; i <= p; i++)	{
			var ab = readline().split(/\s/gi).map(Number),
				a = ab[0], b = ab[1];

			if(abArr[abArr.length - 1][1] < a)	abArr.push(ab);
		}

		for(var j = 1; j <= q; j++)	{
			var cd = readline().split(/\s/gi).map(Number),
				c = cd[0], d = cd[1];

			if(cdArr[cdArr.length - 1][1] < c)	{
				cdArr.push(cd);

				for(var k = 1; k <= abArr.length - 1; k++)	{
					var a = abArr[k][0], b = abArr[k][1],
						sl = a - d, sr = b - c;

					sr > r ? sr = r : true;
					sl < l ? sl = l : true;

					if(sl >= l)	{
						//console.log('%d, %d', sl, sr);
						for(var n = sl; n <= sr; n++)	{
							result[n] = 1;
						}
					}
				}
			}
		}

		print(Object.keys(result).length);

;(function () {
	print(function (p, q, l, r) {
		var t = 0;

		var ab = [];
		while (p--) {
			ab.push(readline().split(' ').map(Number));
		} p = ab.length;

		var cd = [];
		while (q--) {
			cd.push(readline().split(' ').map(Number));
		} q = cd.length;

		for (; l <= r; l++) {
			var w = true;
			for (var i = 0; i < p && w; i++) {
				for (var j = 0; j < q && w; j++) {
					var a = ab[i], b = [cd[j][0] + l, cd[j][1] + l];

					if (Math.max(a[1], b[1]) >= Math.min(a[0], b[0]) && Math.min(a[1], b[1]) >= Math.max(a[0], b[0]) ) {
						t++;
						w = false;
					}
				}
			}
		}

		return t;
	}.apply(null, readline().split(' ').map(Number)));
}.call(this));

function ProblemSolver() {

    this.solveCase = function() {
        var res , i , j , a , b , c , d , e  , k;
        res = 0;
        for( i = 0 ; i < this.p ; i++ ) {
            a = this.arr[ i ];
            b = this.brr[ i ];
            for( j = a ; j <= b ; j++ ) {
                this.err[ j ] = 1;
            }
        }
        for( i = this.l ; i <= this.r ; i++ ) {
            c = 0 ;
            for( j = 0 ; j < this.q ; j++ ) {
                a = this.crr[ j ] + i;
                b = this.drr[ j ] + i;
                for( k = a ; k <= b ; k++ ) {
                    if( this.err[ k ] == 1 ) {
                        c = 1 ;
                        break ;
                    }
                }
            }
            if( c == 1 ) {
                res++ ;
            }
        }
        print( res );
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.p = irObj.nextInt();
            this.q = irObj.nextInt();
            this.l = irObj.nextInt();
            this.r = irObj.nextInt();
            for( i = 0 ; i < this.p ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
                this.brr[ i ] = irObj.nextInt();
            }
            for( i = 0 ; i < this.q ; i++ ) {
                this.crr[ i ] = irObj.nextInt();
                this.drr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.drr = new Array();
        this.err = new Array();
        this.frr = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.crr.push( 0 );
            this.drr.push( 0 );
            this.err.push( 0 );
            this.frr.push( 0 );
            this.adj_list.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        //this.clearArraysPerCase() ;
    };

    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.drr = new Array();
        this.err = new Array();
        this.frr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.crr.push( 0 );
            this.drr.push( 0 );
            this.err.push( 0 );
            this.frr.push( 0 );
            this.adj_list.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init = function() {
        this.lim1 = 1010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.memsetArray1D = function( arrParam , val ) {
        var i;
        if( arrParam == null ) {
            throw new Error( "No array supplied in the parameter!" );
        }
        if( val == null ) {
            throw new Error( "No value for memset has been supplied in the parameter!" );
        }
        arrParam = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            arrParam.push( val );
        }
        return arrParam;
    };

    this.getStringLength = function( stringData ) {
        var len , lengthType;
        len = stringData.length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = stringData.length();
        }
        else {
            len = stringData.length;
        }
        return len;
    };

    this.init();
}

function InputReader() {
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhinoStdin = function() {
        importPackage( java.io );
        importPackage( java.lang );
        var singleLine , reader;
        reader = new BufferedReader( new InputStreamReader( System[ "in" ] ) );
        this.allLines = [];
        while( true ) {
            singleLine = reader.readLine();
            if( singleLine != null ) {
                this.allLines.push( singleLine );
            }
            else {
                break;
            }
        }
    };

    this.readAllLinesFromNodeStdin = function() {
        var fsObj , size , rawData;
        process.stdin.setEncoding( 'ascii' );
        fsObj = require( 'fs' );
        size = fsObj.fstatSync( process.stdin.fd ).size;
        rawData = fsObj.readSync( process.stdin.fd , size )[ 0 ];
        this.parseRawData( rawData );
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx , lengthType;
        len = this.allLines[ this.currrentLineNumber ].length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = this.allLines[ this.currrentLineNumber ].length();
        }
        if( flag == 0 ) {
            res = "";
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != '\t'.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = -1;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) || this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == '\t'.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            if( endIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            else {
                this.currrentCharacterIndex = endIdx;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        if( currentDirectory.charAt( 1 ) != ":" ) {
            //not local machine/windows
            outputFilePath = outputFileName;
        }
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCode = function() {
        var testCases , i , hasMoreTestCases , isLocalMachine , localContext;
        isLocalMachine = false;
        try {
            if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {
                //only on windows
                isLocalMachine = true;
            }
        }
        catch( ex ) {
            isLocalMachine = false;
        }
        if( isLocalMachine == true ) {
            //local machine runs on node and relies on file i/o
            print = console.log;
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
        }
        else {
            //server machine
            try {
                var rlObj = readline;
                //server runs on javasctipt v8 distribution and has readline method on global context
                this.irObj.readAllLines();
            }
            catch( ex ) {
                try {
                    var pObj = process;
                    //server runs on node
                    print = console.log;
                    this.irObj.readAllLinesFromNodeStdin();
                }
                catch( ex ) {
                    try {
                        var ipObj = importPackage;
                        //server runs on rhino
                        this.irObj.readAllLinesFromRhinoStdin();
                    }
                    catch( ex ) {
                        throw new Error( "Unknown javasctipt distribution!" );
                    }
                }
            }
        }
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            //only works for local machine(tested)
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.runCode();
}

new CodeExecutioner();

var p = readline().split(/\s/gi).map(Number),
			q = p[1], l = p[2], r = p[3], p = p[0],
			abArr = [ [ -1, -1 ] ], cdArr = [ [ -1, -1 ] ], result = {};

		for(var i = 1; i <= p; i++)	{
			var ab = readline().split(/\s/gi).map(Number),
				a = ab[0], b = ab[1];

			if(abArr[abArr.length - 1][1] < a)	abArr.push(ab);
		}

		for(var i = 1; i <= q; i++)	{
			var cd = readline().split(/\s/gi).map(Number),
				c = cd[0], d = cd[1];

			if(cdArr[cdArr.length - 1][1] < c)	{
				cdArr.push(cd);

				for(var k = 1; k <= p; k++)	{
					var a = abArr[k][0], b = abArr[k][1],
						sl = a - d, sr = b - c;

					sr > r ? sr = r : true;
					sl < 0 ? sl = 0 : true;

					if(sl >= 0)	{
						//console.log('%d, %d', sl, sr);
						for(var n = sl; n <= sr; n++)	{
							result[n] = 1;
						}
					}
				}
			}
		}

		print(Object.keys(result).length);

var p = readline().split(/\s/gi).map(Number),
			q = p[1], l = p[2], r = p[3], p = p[0],
			abArr = [ [ -1, -1 ] ], cdArr = [ [ -1, -1 ] ], result = {};

		for(var i = 1; i <= p; i++)	abArr.push(readline().split(/\s/gi).map(Number));
		for(var i = 1; i <= q; i++)	{
			var cd = readline().split(/\s/gi).map(Number),
				c = cd[0], d = cd[1];

			if(cdArr[cdArr.length - 1][1] < c)	{
				for(var k = 1; k <= p; k++)	{
					var a = abArr[k][0], b = abArr[k][1],
						sl = a - d, sr = b - c;

					sr > r ? sr = r : true;
					sl < 0 ? sl = 0 : true;

					if(sl >= 0)	{
						//console.log('%d, %d', sl, sr);
						for(var n = sl; n <= sr; n++)	{
							result[n] = 1;
						}
					}
				}
			}
		}

		print(Object.keys(result).length);

var p = readline().split(/\s/gi).map(Number),
			q = p[1], l = p[2], r = p[3], p = p[0],
			abArr = [ [ -1, -1 ] ], cdArr = [ [ -1, -1 ] ], result = {};

		for(var i = 1; i <= p; i++)	{
			var ab = readline().split(/\s/gi).map(Number),
				a = ab[0], b = ab[1];

			if(abArr[abArr.length - 1][1] < a)	abArr.push(ab);
		}

		for(var j = 1; j <= q; j++)	{
			var cd = readline().split(/\s/gi).map(Number),
				c = cd[0], d = cd[1];

			if(cdArr[cdArr.length - 1][1] < c)	{
				cdArr.push(cd);

				for(var k = 1; k <= abArr.length - 1; k++)	{
					var a = abArr[k][0], b = abArr[k][1],
						sl = a - d, sr = b - c;

					sr > r ? sr = r : true;
					sl < 0 ? sl = 0 : true;

					if(sl >= 0)	{
						//console.log('%d, %d', sl, sr);
						for(var n = sl; n <= sr; n++)	{
							result[n] = 1;
						}
					}
				}
			}
		}

		print(Object.keys(result).length);


function key(a, b) {
  return a + ',' + b;
}
function gcd( a,  b)
{
    /* GCD(0, b) == b; GCD(a, 0) == a,
       GCD(0, 0) == 0 */
    if (a == 0)
        return b;
    if (b == 0)
        return a;

    /*Finding K, where K is the
      greatest power of 2
      that divides both a and b. */
    var k;
    for (k = 0; ((a | b) & 1) == 0; ++k)
    {
        a >>= 1;
        b >>= 1;
    }

    /* Dividing a by 2 until a becomes odd */
    while ((a & 1) == 0)
        a >>= 1;

    /* From here on, 'a' is always odd. */
    do
    {
        /* If b is even, remove all factor of 2 in b */
        while ((b & 1) == 0)
            b >>= 1;

        /* Now a and b are both odd.
           Swap if necessary so a <= b,
           then set b = b - a (which is even).*/
        if (a > b){
        var t = a;
        a = b;
        b = t;
        }

        b = (b - a);
    } while (b != 0);

    /* restore common factors of 2 */
    return a << k;
}

function woodSplits(str) {
  var dilucCount = 0;
  var kayeaCount = 0;
  var countsMap = {};
  var answer = [];
  for (var i = 0; i < str.length; i++) {
    if (str[i] == 'D') {
      dilucCount++;
    } else if (str[i] == 'K') {
      kayeaCount++;
    }
    var currentGcd = gcd(dilucCount, kayeaCount);
    var currentKey = key(dilucCount / currentGcd, kayeaCount / currentGcd);
    var newValue = 1 + (countsMap[currentKey] || 0);
    countsMap[currentKey] = newValue;
    answer.push(newValue);
  }
  return answer;
}

var numCases = Number(readline());
for (var i = 0; i < numCases; i++) {
  readline();
  var str = readline();
  print(woodSplits(str).join(' '));
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var n = Number(read());
   var str = read();
   var dcount = [0];
   var kcount = [0];
   var save = new Map();
   for(var i = 0; i < n; i++) {
      if (str[i] === 'D') {
         dcount.push(dcount[i] + 1);
         kcount.push(kcount[i]);
         continue;
      }
      dcount.push(dcount[i]);
      kcount.push(kcount[i] + 1);
   }
   var ans = [];
   for (var i = 1; i <= n; i++) {
      if (dcount[i] === 0 || kcount[i] === 0) {
         ans.push(dcount[i] + kcount[i]);
         continue;
      }
      var countGcd = gcd(dcount[i], kcount[i]);
      var strSave = div(dcount[i], countGcd) + ':' + div(kcount[i], countGcd);
      if (countGcd === 1) {
         ans.push(1);
         save.set(strSave, 1);
         continue;
      }
      if (save.has(strSave)) {
         var curAns = save.get(strSave) + 1;
         ans.push(curAns);
         save.set(strSave, curAns);
         continue;
      }
      ans.push(1);
      save.set(strSave, 1);
   }
   write(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 {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      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 readAll() {
   return isNode && MEMORY;
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var n = Number(read());
   var str = read();
   var dcount = [0];
   var kcount = [0];
   var save = {};
   for(var i = 0; i < n; i++) {
      if (str[i] === 'D') {
         dcount.push(dcount[i] + 1);
         kcount.push(kcount[i]);
         continue;
      }
      dcount.push(dcount[i]);
      kcount.push(kcount[i] + 1);
   }
   var ans = [];
   for (var i = 1; i <= n; i++) {
      if (dcount[i] === 0 || kcount[i] === 0) {
         ans.push(dcount[i] + kcount[i]);
         continue;
      }
      var countGcd = gcd(dcount[i], kcount[i]);
      var strSave = div(dcount[i], countGcd) + ':' + div(kcount[i], countGcd);
      if (countGcd === 1) {
         ans.push(1);
         save[strSave] = 1;
         continue;
      }
      if (save[strSave]) {
         var curAns = save[strSave] + 1;
         ans.push(curAns);
         save[strSave] = curAns;
         continue;
      }
      ans.push(1);
      save[strSave] = 1;
   }
   write(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 {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      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 readAll() {
   return isNode && MEMORY;
}

'use strict';

function solve(n, s) {
  const map = new Map();
  const dp = [];
  let d = 0,
      k = 0;
  for (let i = 0; i < n; i++) {
    if (s[i] === 'D') d++;else k++;
    const a = gcd(d, k),
          b = d / a,
          c = k / a,
          r = `${b},${c}`;
    if (map.has(r)) {
      dp[i] = dp[map.get(r)] + 1;
    } else {
      dp[i] = 1;
    }
    map.set(r, i);
  }
  return dp.join(' ');
}
function gcd(a, b) {
  return !b ? a : gcd(b, a % b);
}

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

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var len = +readline();
    var tree = readline();
    var ds = 0;
    var ks = 0;
    var mp = {};
    var results = [];
    for (var j = 0; j < len; j++) {
      tree[j] === 'D' ? ds++ : ks++;
      var key = `d${ds/nod(ds, ks)}k${ks/nod(ds, ks)}`;
      mp[key] = mp[key] ? ++mp[key] : 1;
      results.push(mp[key]);
    }
    print(results.join(' '));
  }
}

function nod(a, b) {
  if (b === 0) {
    return a;
  }
  return nod(b, a % b);
}
main();

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const gcd = (a, b) => b ? gcd(b, a % b) : a;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		const ans = [];
		const m = new Map();
		for (let i = 0, d = 0, k = 0; i < n; i++) {
			d += s[i] == 'D';
			k += s[i] == 'K';

			const ratio = d / gcd(d, k) + ':' + k / gcd(d, k);
			ans[i] = 1 + (m.get(ratio) || 0);
			m.set(ratio, ans[i]);
		}

		console.log(ans.join(' '));
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		const ans = [];
		const mp = new Map();
		for (let i = 0, cnt = 0; i < n; i++) {
			cnt += s[i] == 'D';

			const cur = mp.get(cnt/(i+1)) || 1;
			ans[i] = cur;
			mp.set(cnt/(i+1), cur + 1);
		}

		console.log(ans.join(' '));
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const mxN = 5e5 + 100;

const fact = Array.from(Array(mxN+1), x => []);

function computeFactors () {
	for (let i = 1; i <= mxN; i++) {
		let j = i;
		while (j <= mxN) {
			fact[j].push(i);
			j += i;
		}
	}
}

function main () {
	computeFactors();
	//console.log(fact[10], fact[100]);
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		const dp = [];
		const cnt = []; cnt[-1] = 0;
		const ans = [];
		for (let i = 0; i < n; i++) {
			cnt[i] = cnt[i-1] + (s[i] == 'D');
			//console.log({cnt})
			for (const f of fact[i+1]) {
				const dCnt = cnt[i] - cnt[i-f];
				const ration = dCnt / f;
				//console.log({i, f, dCnt, ration})
				if (ration == dp[i-f]) {
					dp[i] = ration;
					ans[i] = ans[i-f]+1;
					break;
				}
				if (f == i+1) {
					dp[i] = ration;
					ans[i] = 1;
				}
			}
			//console.log({cnt});
		}

		console.log(ans.join(' '));
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const mxN = 5e5 + 100;

const fact = Array.from(Array(mxN+1), x => []);

function computeFactors () {
	for (let i = 1; i <= mxN; i++) {
		let j = i;
		while (j <= mxN) {
			fact[j].push(i);
			j += i;
		}
	}
}

function main () {
	computeFactors();
	//console.log(fact[10], fact[100]);
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		const dp = [];
		const cnt = []; cnt[-1] = 0;
		const ans = [];
		for (let i = 0; i < n; i++) {
			cnt[i] = cnt[i-1] + (s[i] == 'D');
			//console.log({cnt})
			for (const f of fact[i+1]) {
				const dCnt = cnt[i] - cnt[i-f];
				const ration = dCnt / f;
				//console.log({i, f, dCnt, ration})
				if (ration == dp[i-f] && ans[i-f] == (i-f+1)/f) {
					dp[i] = ration;
					ans[i] = (i+1)/f;
					break;
				}
				if (f == i+1) {
					dp[i] = ration;
					ans[i] = 1;
				}
			}
			//console.log({cnt});
		}
			//console.log({dp});

		console.log(ans.join(' '));
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const mxN = 5e5 + 100;

const fact = Array.from(Array(mxN+1), x => []);

function computeFactors () {
	for (let i = 1; i <= mxN; i++) {
		let j = i;
		while (j <= mxN) {
			fact[j].push(i);
			j += i;
		}
	}
}

function main () {
	computeFactors();
	//console.log(fact[10], fact[100]);
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		const dp = [];
		const cnt = []; cnt[-1] = 0;
		const ans = [];
		for (let i = 0; i < n; i++) {
			cnt[i] = cnt[i-1] + (s[i] == 'D');
			//console.log({cnt})
			for (const f of fact[i+1]) {
				const dCnt = cnt[i] - cnt[i-f];
				const ration = dCnt / f;
				//console.log({i, f, dCnt, ration})
				if (ration == dp[i-f] || f == i+1) {
					dp[i] = ration;
					ans[i] = (i+1)/f;
					break;
				}
			}
			//console.log({dp});
			//console.log({cnt});
		}

		console.log(ans.join(' '));
	}
}

var cache = {};
function key(a, b) {
  return a + ',' + b;
}
// https://en.wikipedia.org/wiki/Greatest_common_divisor
function gcd(a, b){
  if(key(a, b) in cache) return cache[key(a, b)];

  var result = b === 0 ? a : gcd(b, a % b);
  cache[key(a, b)] = result;
  return result;
}

function woodSplits(str) {
  var dilucCount = 0;
  var kayeaCount = 0;
  var countsMap = {};
  var answer = [];
  for (var i = 0; i < str.length; i++) {
    if (str[i] == 'D') {
      dilucCount++;
    } else if (str[i] == 'K') {
      kayeaCount++;
    }
    var currentGcd = gcd(dilucCount, kayeaCount);
    var currentKey = key(dilucCount / currentGcd, kayeaCount / currentGcd);
    var newValue = 1 + (countsMap[currentKey] || 0);
    countsMap[currentKey] = newValue;
    answer.push(newValue);
  }
  return answer;
}

var numCases = Number(readline());
for (var i = 0; i < numCases; i++) {
  readline();
  var str = readline();
  print(woodSplits(str));
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var len = +readline();
    var tree = readline();
    var ds = 0;
    var ks = 0;
    var results = [];
    for (var j = 0; j < len; j++) {
      tree[j] === 'D' ? ds++ : ks++;
      var max = ds > ks ? ds : ks;
      var min = ds < ks ? ds : ks;
      if (min === 0) {
        results.push(max);
      } else if (max % min === 0) {
        results.push(min)
      } else { results.push(1) }
    }
    print(results.join(' '));
  }
}

main();


const lines = [];
const _rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
_rl.on('line', line => lines.push(line));
_rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);
const rl = readline;

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const sumab = (a, b) => {
    if (a > b) return 0;
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return x * y;
}

const calc = (t)=>{
    /* read */
    let [n, k] = ra();
    let a = ra();

    if (n === 1) {
        return a[0] + k - 1;
    }

    if (k <= n) {
        let i = 0;
        let curSum = 0;
        for (; i < k; i++) {
            curSum += a[i];
        }
        let maxSum = curSum;
        for (; i < n; i++) {
            curSum += a[i];
            curSum -= a[i - k];
            maxSum = Math.max(maxSum, curSum);
        }
        return maxSum + sumab(1, k - 1);
    } else {
        let sum = 0;
        for (let i = 0; i < n; i++) {
            sum += a[i];
        }
        // console.log(`DEBUG t ${t} sum`, sum);
        let wait = k - n;
        // console.log(`DEBUG t ${t} wait`, wait);
        let traverse = sumab(wait + 1, wait + n - 1);
        // console.log(`DEBUG t ${t} traverse`, traverse);
        let result = sum + wait + traverse;
        return result;
    }
};

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

"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() {
    const t = readline()
    for(let _=0;_<t;_++) {
        const [n, k] = readline().split(' ').map(Number)
        const arr = readline().split(' ').map(Number)
        let answer = 0

        let sum_list = Array(n+1).fill(0)
        sum_list[1] = arr[0]

        for (let i=2;i<n+1;i++) {
            sum_list[i] = sum_list[i-1] + arr[i-1]
        }
        if (n < k) {
            answer = sum_list[n] + parseInt(n * (n - 1) / 2) + n * (k - n)
        } else {
            for(let i=k;i<n+1;i++){
                answer = Math.max(answer, sum_list[i] - sum_list[i-k])
            }
            answer += parseInt(k * (k - 1) / 2)
        }
        print(answer)
    }

}

'use strict';

function solve(n, m, a) {
  const bm = BigInt(m),
        bn = BigInt(n);
  if (m >= n) {
    return (a.reduce((a, b) => a + b, 0n) + bm * (bm - 1n) / 2n - (bm - bn) * (bm - bn - 1n) / 2n).toString();
  }
  const sum = [];
  let max = 0n;
  for (let [i, num] of a.entries()) {
    var _sum, _sum2;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0n) + num;
    const cur = sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0n);
    if (max < cur) max = cur;
  }
  return (max + bm * (bm - 1n) / 2n).toString();
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(BigInt);
      res.push(solve(n, m, a));
    }
    console.log(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', () => {
  inputs = str.split('\n').values();
  main(read);
});

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            if (k <= after) {
                const now = range(i, i + k - 1)
                if (now > max) max = now
            }
            // console.log(now)
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(n - 2 - before + 1, n - 2)
            }
            if (now > max) max = now
            // console.log(now)
            if (i + 1 < k) {
                const before = k - (i + 1)
                now = range(1, 1 + before - 1) + range(0, i)
                if (now > max) max = now
                // console.log(now)
            }
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(n - 1 - before + 1, n - 1)
            }
            if (now > max) max = now
            // console.log(now)
            if (i + 1 < k) {
                const before = k - (i + 1)
                now = range(0, before - 1) + range(0, i)
                if (now > max) max = now
                // console.log(now)
            }
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(n - 1 - before + 1, n - 1)
            }
            if (now > max) max = now
            // console.log(now)
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(0, before - 1)
            }
            if (now > max) max = now
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

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

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const sumab = (a, b) => {
    if (a > b) return 0;
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return x * y;
}

const calc = (t)=>{
    /* read */
    let [n, k] = ra();
    let a = ra();

    if (n === 1) {
        return a[0] + k - 1;
    }

    if (k < n) {
        let i = 0;
        let curSum = 0;
        for (; i < k; i++) {
            curSum += a[i];
        }
        let maxSum = curSum;
        for (; i < n; i++) {
            curSum += a[i];
            curSum -= a[i - k];
            maxSum = Math.max(maxSum, curSum);
        }
        return maxSum + sumab(1, k - 1);
    } else {
        let start = k % n;
        // console.log(`DEBUG t ${t} start`, start);
        let sum = 0;
        for (let i = 0; i < n; i++) {
            sum += a[i];
        }
        let initial = start + n;
        // console.log(`DEBUG t ${t} initial`, initial);
        let cycles = Math.floor((k - initial) / (n - 1) + 0.000001);
        // console.log(`DEBUG t ${t} cycles`, cycles);

        let result = sumab(1, n - 1) * 2 * cycles + sum;
        // console.log(`DEBUG t ${t} result1`, result);

        let remMoves = k - initial - cycles * (n - 1);
        // console.log(`DEBUG t ${t} remMoves`, remMoves);
        result += sumab(1, remMoves) * 2;
        // console.log(`DEBUG t ${t} result2`, result);

        result += sumab(1, start) + sumab(1, start - 1) * 2;
        // console.log(`DEBUG t ${t} result3`, result);

        let rem = n - start;
        // console.log(`DEBUG t ${t} rem`, rem);
        let ns = start * 2;
        result += sumab(ns, ns + rem - 1);
        // console.log(`DEBUG t ${t} result4`, result);
        return result;
    }
};

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

'use strict';

function solve(n, m, a) {
  if (m >= n) {
    return a.reduce((a, b) => a + b, 0) + m * (m - 1) / 2 - (m - n) * (m - n - 1) / 2;
  }
  const sum = [];
  let max = 0;
  for (let [i, num] of a.entries()) {
    var _sum, _sum2;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + num;
    max = Math.max(max, sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0));
  }
  return max + m * (m - 1) / 2;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, m, a));
    }
    console.log(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', () => {
  inputs = str.split('\n').values();
  main(read);
});