var lll = readline().split(' ')
var n = lll[0]
var P1 = lll[1]
var P2 = lll[2]
var P3 = lll[3]
var T1 = lll[4]
var T2 = lll[5]

var ss = []

while (lll = readline()) ss.push(lll.split(' '))

var pows = 0
var pse

for (var i = 0; i < n; i++) {
  var s = ss[i]
  pows += (s[1] - s[0]) * P1
  if (pse) {
    var w = s[0] - pse
    pows += Math.min(w, T1) * P1
    w -= T1
    if (w > 0) {
      pows += Math.min(w, T2) * P2
      w -= T2
      if (w > 0) {
        pows += w * P3
      }
    }
  }
  pse = s[1]
}

print(pows)

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

var arr = []
var intervals = [];
var counter = 0;
var n = 1000;
var ans = 0;

var P1;
var P2;
var P3;
var T1;
var T2;
rl.on('line', function (line) {
    if (arr.length == 0) {
        arr = line.split(' ').map(item => { return parseInt(item) });
        n = arr[0];
        P1 = arr[1];
        P2 = arr[2];
        P3 = arr[3];
        T1 = arr[4];
        T2 = arr[5];
       /* console.log(n,P1,P2,P3,T1,T2);
        console.log(arr);
        console.log("line = "+line);*/
    }
    else {

        if (++counter < n) {

            intervals.push(line.split(' ').map(item => { return parseInt(item) }));
        }
        else {
            intervals.push(line.split(' ').map(item => { return parseInt(item) }));

           /* console.log("intervals.length= " + intervals.length)
            console.log(n,P1,P2,P3,T1,T2);
            console.log*/
            ans += (intervals[0][1] - intervals[0][0]) * P1;

            for (let i = 1; i < n; i++) {
                ans += (intervals[i][1] - intervals[i][0]) * P1;

                gap = intervals[i][0] - intervals[i - 1][1];
                if (gap >= T1) {
                    ans += T1 * P1;
                    gap -= T1;
                }
                else {
                    ans += gap * P1;
                    gap = 0;
                }

                if (gap >= T2) {
                    ans += T2 * P2;
                    gap -= T2;
                }
                else {
                    ans += gap * P2;
                    gap = 0;
                }
                ans += gap * P3;
            }
            console.log(ans);
            rl.close();
        }

    }

});

function solve(p_1, p_2, p_3, t_1, t_2, lrs) {
  const t = t_1 + t_2;
  let [p_l, p_r] = lrs.shift();
  let result = (p_r - p_l) * p_1;
  for (const [c_l, c_r] of lrs) {
    let d = c_l - p_r;
    if (d > t) {
      result = result + (p_1 * t_1) + (p_2 * t_2) + (p_3 * (d - t));
    } else if (d > t_1) {
      result = result + (p_1 * t_1) + (p_2 * (d - t_1));
    } else {
      result = result + (p_1 * d);
    }
    result = result + ((c_r - c_l) * p_1);
    p_l = c_l;
    p_r = c_r;
  }
  return result;
};

function main(lines) {
  const [n, p_1, p_2, p_3, t_1, t_2] = lines.shift().trim().split(/\s+/).map(Number);
  const lrs = [];
  for (const line of lines) {
    const t = line.trim();
    if (t.length > 0) {
      const lr = t.split(/\s+/).map(Number);
      lrs.push(lr);
    }
  }
  const result = solve(p_1, p_2, p_3, t_1, t_2, lrs)
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding('utf-8');
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

function solve(p_1, p_2, p_3, t_1, t_2, lrs) {
  const t = t_1 + t_2;
  const p_lr = lrs.shift();
  let [p_l, p_r] = p_lr;
  let result = (p_r - p_l) * p_1;
  for (const [c_l, c_r] of lrs) {
    let d = c_l - p_r;
    if (d > t) {
      result = result + (p_1 * t_1) + (p_2 * t_2) + (p_3 * (d - t));
    } else if (d > t_1) {
      result = result + (p_1 * t_1) + (p_2 * (d - t_1));
    } else {
      result = result + (p_1 * d);
    }
    result = result + ((c_r - c_l) * p_1);
    p_l = c_l;
    p_r = c_r;
  }
  return result;
};

function main(lines) {
  const [n, p_1, p_2, p_3, t_1, t_2] = lines.shift().trim().split(/\s+/).map(Number);
  const lrs = [];
  for (const line of lines) {
    const t = line.trim();
    if (t.length > 0) {
      const lr = t.split(/\s+/).map(Number);
      lrs.push(lr);
    }
  }
  const result = solve(p_1, p_2, p_3, t_1, t_2, lrs)
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding('utf-8');
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

const readline = require("readline");

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

var array = [];
var n = -1;
var P1 = 0;
var P2 = 0;
var P3 = 0;
var T1 = 0;
var T2 = 0;
var answer = 0;
var temp = 1440;

rl.on("line", input => {
  if (n == -1) {
    array = input.split(" ");
     n = parseInt(array[0]);
     P1 = parseInt(array[1]);
     P2 = parseInt(array[2]);
     P3 = parseInt(array[3]);
     T1 = parseInt(array[4]);
     T2 = parseInt(array[5]);
  } else if (n > 0) {
    array = input.split(" ");
    var start = parseInt(array[0]);
    var end = parseInt(array[1]);

    answer += (end - start) * P1;

    var deference = start - temp > 0 ? start - temp : 0;
    if (T1 < deference) {
      answer += P1 * T1;
      if ((deference - T1) > T2) {
        answer += P2 * T2;
        if (deference - (T1 + T2) > 0) answer += P3 * (deference - (T1 + T2));
      }
      else answer+= (deference-T1)*P2;
    } else if (deference > 0) answer += P1 * deference;
    temp = end;
    n--;
  }
}).on("close", () => {
  console.log(answer);
});

const readline = require('readline');

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

var ans = 0,
    n, P1, P2, P3, T1, T2, indicator = 0,
    l1, r1, l2, r2, cont, gap;

rl.on('line', (input) => {
    if (indicator == 0) {
        cont = input.split(' ').map(item => parseInt(item));
        n = cont[0], P1 = cont[1], P2 = cont[2], P3 = cont[3], T1 = cont[4], T2 = cont[5];
        indicator++;
    } else if (indicator== 1) {
        cont = input.split(' ').map(item => parseInt(item));
        l1 = cont[0], r1 = cont[1];
        ans += (r1 - l1) * P1;
        indicator++;
    } else {
        cont = input.split(' ').map(item => parseInt(item));
        l2 = cont[0], r2 = cont[1];
        //oconsole.log("l1=%d  r1=%d    l2=%d  r2=%d     ans=%d",l1,r1,l2,r2,ans);
        ans += (r2 - l2) * P1;
        gap = l2 - r1;
        if (gap > T1) {
            ans += T1 * P1;
            gap -= T1;
        } else {
            ans += gap * P1;
            gap = 0;
        }
        if (gap > T2) {
            ans += T2 * P2;
            gap -= T2;
        } else {
            ans += gap * P2;
            gap = 0;
        }
        ans += gap * P3;

        l1 = l2;
        r1 = r2;
    }

}).on('close', () => {

    console.log(ans);
    rl.close();
});

var data = readline().split(' ').map(item => parseInt(item));
var n = data[0];
var p1 = data[1], p2 = data[2], p3 = data[3];
var t1 = data[4], t2 = data[5];
power = 0;
data = [];
for(var i = 0; i < n; i++) {
  data.push(readline().split(' ').map(item => parseInt(item)));
  power += (data[i][1] - data[i][0]) * p1;
}
for(var i = 0; i < n - 1; i++) {
  var time = data[i + 1][0] - data[i][1];
  var ans = Math.min(time, t1);
  power += ans * p1;
  time -= ans;
  if(time < 0) {
    continue;
  }
  ans = Math.min(time, t2);
  power += ans * p2;
  time -= ans;
  power += time * p3;
}
print(power);

var lll = readline().split(' ')
var n = lll[0]
var P1 = lll[1]
var P2 = lll[2]
var P3 = lll[3]
var T1 = lll[4]
var T2 = lll[5]

var ss = []

while (lll = readline()) ss.push(lll.split(' '))

var pows = 0
var pse

for (var i = 0; i < ss.length; i++) {
  var s = ss[i]
  pows += (s[1] - s[0]) * P1
  if (pse) {
    var w = s[0] - pse
    pows += Math.min(w, T1) * P1
    w -= T1
    if (w) {
      pows += Math.min(w, T2) * P2
      w -= T2
      if (w) {
        pows += w * P3
      }
    }
  }
  pse = s[1]
}

print(pows)

function solve(p_1, p_2, p_3, t_1, t_2, lrs) {
  const t = t_1 + t_2;
  const [p_l, p_r] = lrs.shift();
  let result = (p_r - p_l) * p_1;
  for (const [c_l, c_r] of lrs) {
    let d = c_l - p_r;
    if (d > t) {
      result = result + (p_1 * t_1) + (p_2 * t_2) + (p_3 * (d - t));
    } else if (d > t_1) {
      result = result + (p_1 * t_1) + (p_2 * (d - t_1));
    } else {
      result = result + (p_1 * d);
    }
    result = result + ((c_r - c_l) * p_1);
    p_l = c_l;
    p_r = c_r;
  }
  return result;
};

function main(lines) {
  const [n, p_1, p_2, p_3, t_1, t_2] = lines.shift().trim().split(/\s+/).map(Number);
  const lrs = [];
  for (const line of lines) {
    const t = line.trim();
    if (t.length > 0) {
      const lr = t.split(/\s+/).map(Number);
      lrs.push(lr);
    }
  }
  const result = solve(p_1, p_2, p_3, t_1, t_2, lrs)
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding('utf-8');
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

function solve(p_1, p_2, p_3, t_1, t_2, lrs) {
  const t = t_1 + t_2;
  const p_lr = lrs.shift();
  const [p_l, p_r] = p_lr;
  let result = (p_r - p_l) * p_1;
  for (const [c_l, c_r] of lrs) {
    let d = c_l - p_r;
    if (d > t) {
      result = result + (p_1 * t_1) + (p_2 * t_2) + (p_3 * (d - t));
    } else if (d > t_1) {
      result = result + (p_1 * t_1) + (p_2 * (d - t_1));
    } else {
      result = result + (p_1 * d);
    }
    result = result + ((c_r - c_l) * p_1);
  }
  return result;
};

function main(lines) {
  const [n, p_1, p_2, p_3, t_1, t_2] = lines.shift().trim().split(/\s+/).map(Number);
  const lrs = [];
  for (const line of lines) {
    const t = line.trim();
    if (t.length > 0) {
      const lr = t.split(/\s+/).map(Number);
      lrs.push(lr);
    }
  }
  const result = solve(p_1, p_2, p_3, t_1, t_2, lrs)
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding('utf-8');
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

const readline = require("readline");

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

var array = [];
var n = -1;
var P1 = 0;
var P2 = 0;
var P3 = 0;
var T1 = 0;
var T2 = 0;
var answer = 0;
var temp = 1440;

rl.on("line", input => {
  if (n == -1) {
    array = input.split(" ");
     n = parseInt(array[0]);
     P1 = parseInt(array[1]);
     P2 = parseInt(array[2]);
     P3 = parseInt(array[3]);
     T1 = parseInt(array[4]);
     T2 = parseInt(array[5]);
  } else if (n > 0) {
    array = input.split(" ");
    var start = parseInt(array[0]);
    var end = parseInt(array[1]);

    answer += (end - start) * P1;

    var deference = start - temp > 0 ? start - temp : 0;
    if (T1 < deference) {
      answer += P1 * T1;
      if (deference - T1 > T2) {
        answer += P2 * T2;
        if (deference - (T1 + T2) > 0) answer += P3 * (deference - (T1 + T2));
      }
    } else if (deference > 0) answer += P1 * deference;
    temp = end;
    n--;
  }
}).on("close", () => {
  console.log(answer);
});

const readline = require('readline');

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

var ans = 0,
    n, P1, P2, P3, T1, T2, indicator = 0,
    l1, r1, l2, r2, cont, gap;

rl.on('line', (input) => {
    if (indicator == 0) {
        cont = input.split(' ').map(item => parseInt(item));
        n = cont[0], P1 = cont[1], P2 = cont[2], P3 = cont[3], T1 = cont[4], T2 = cont[5];
        indicator++;
    } else if (indicator == 1) {
        cont = input.split(' ').map(item => parseInt(item));
        l1 = cont[0], r1 = cont[1];
        ans += (r1 - l1) * P1;
        indicator++;
    } else {
        cont = input.split(' ').map(item => parseInt(item));
        l2 = cont[0], r2 = cont[1];
        ans += (r2 - l2) * P1;
        gap = l2 - r1;
        if (gap > T1) {
            ans += T1 * P1;
            gap -= T1;
        } else {
            ans += gap * P1;
            gap = 0;
        }
        if (gap > T2) {
            ans += T2 * P2;
            gap -= T2;
        } else {
            ans += gap * P2;
            ans = 0;
        }
        ans += gap * P3;

        l1 = l2;
        r1 = r2;
    }

}).on('close', () => {

    console.log(ans);
    rl.close();
});


'use strict';

var fs = require('fs');

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

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

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

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

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).sort((a, b) => a - b);

        let result = 0
        for(let i = 0; i < A.length - 2; i++) {
            result = Math.max(result, A[A.length-1]-A[i]+A[i+1]-A[i])
        }
        for(let i = 1; i < A.length - 1; i++) {
            result = Math.max(result, A[i+1]-A[0]+A[i+1]-A[i])
        }
        console.log(result)

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).reduce((a, b) => {
            if (a.indexOf(b) < 0) a.push(b);
            return a;
        }, []).sort((a, b) => a - b);

        let result = 0
        for(let i = 0; i < A.length - 2; i++) {
            result = Math.max(result, A[A.length-1]-A[i]+A[i+1]-A[i])
        }
        for(let i = 1; i < A.length - 1; i++) {
            result = Math.max(result, A[i+1]-A[0]+A[i+1]-A[i])
        }
        console.log(result)

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).reduce((a, b) => {
            if (a.indexOf(b) < 0) a.push(b);
            return a;
        }, []).sort((a, b) => a - b);

        if (A.length == 1) {
            console.log(0)
        } else if (A.length == 2) {
            console.log(2 * (A[1] - A[0]))
        } else {
            const p1 = A[A.length - 1] + A[1] - 2 * A[0]
            const p2 = 2 * A[A.length - 1] - A[0] - A[A.length - 2]
            console.log(Math.max(p1, p2))
        }

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).reduce((a, b) => {
            if (a.indexOf(b) < 0) a.push(b);
            return a;
        }, []).sort((a, b) => a - b);

        console.log(A)

        if (A.length == 1) {
            console.log(0)
        } else if (A.length == 2) {
            console.log(2 * (A[1] - A[0]))
        } else {
            const p1 = A[A.length - 1] + A[1] - 2 * A[0]
            const p2 = 2 * A[A.length - 1] - A[0] - A[A.length - 2]
            console.log(Math.max(p1, p2))
        }

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).reduce((a, b) => {
            if (a.indexOf(b) < 0) a.push(b);
            return a;
        }, []).sort((a, b) => a - b);

        if (A.length == 1) {
            console.log(0)
        } else if (A.length == 2) {
            console.log(2 * (A[1] - A[0]))
        } else {
            const p1 = A[A.length - 1] + A[0] - 2 * A[1]
            const p2 = 2 * A[A.length - 1] - A[A.length - 2] - A[0]
            console.log(Math.max(p1, p2))
        }

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).reduce((a, b) => {
            if (a.indexOf(b) < 0) a.push(b);
            return a;
        }, []).sort((a, b) => a - b);

        if (A.length == 1) {
            console.log(0)
        } else if (A.length == 2) {
            console.log(2 * (A[1] - A[0]))
        } else {
            const p1 = 2 * A[A.length - 1] - A[A.length - 2] - A[0]
            const p2 = 2 * A[0] - A[1] - A[A.length - 1]
            console.log(Math.max(p1, p2))
        }

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const A = lines[line++].split(' ').map(x => parseInt(x, 10)).reduce((a, b) => {
            if (a.indexOf(b) < 0) a.push(b);
            return a;
        }, []).sort((a, b) => a - b);

        console.log(A)

        if (A.length == 1) {
            console.log(0)
        } else if (A.length == 2) {
            console.log(2 * (A[1] - A[0]))
        } else {
            const p1 = 2 * A[A.length - 1] - A[A.length - 2] - A[0]
            const p2 = 2 * A[0] - A[1] - A[A.length - 1]
            console.log(Math.max(p1, p2))
        }

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const a = lines[line++].split(' ').map(x => parseInt(x, 10))
        let max = -1, min = a[0], second = -1;

        for (let i = 0; i < n; i++) {
            if (max <= a[i]) {
                second = max
                max = a[i]
            } else if (second <= a[i]) {
                second = a[i]
            }
            if (min > a[i])
                min = a[i]
        }

        console.log((max - second) + (max - min))

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const a = lines[line++].split(' ').map(x => parseInt(x, 10))
        let max = -1, min = a[0], second = -1;

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

        console.log((max - second) + (max - min))

    }
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    const T = parseInt(lines[0])
    let line = 1
    for (let t = 1; t <= T; t++) {
        const n = parseInt(lines[line++].split(' ')[0], 10)
        const a = lines[line++].split(' ').map(x => parseInt(x, 10))
        let max = a[0], min = a[0], second = -1;

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

        console.log((max - second) + (max - min))

    }
}

'use strict';

var fs = require('fs');

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

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

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

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


const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, x] = input[index].split(" ").map((item) => parseInt(item));
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      x,
      a,
    };

    testCases.push(testCase);
  }
}

function solution(testCase, index) {
  const { n, x, a } = testCase;
  // console.log(n, x, a);

  let result = 0;

  let sum = 0;
  b = a
    .sort((c, d) => c - d)
    .map((v) => {
      sum += v;
      return sum;
    });
  // console.log(b);

  let day = 0;
  let couldBuyOnPreviousDay = n;
  while (x >= b[0] + day) {
    let couldBuyThisDay;
    for (
      couldBuyThisDay = couldBuyOnPreviousDay - 1;
      couldBuyThisDay >= 0;
      couldBuyThisDay--
    ) {
      if (x >= b[couldBuyThisDay] + (couldBuyThisDay + 1) * day) {
        break;
      }
    }
    const nbAdditionDays =
      couldBuyThisDay > -1
        ? Math.floor(
            (x - (b[couldBuyThisDay] + (couldBuyThisDay + 1) * day)) /
              (couldBuyThisDay + 1)
          )
        : 0;
    // console.log("day", day);
    // console.log("nbAdditionDays", nbAdditionDays);
    result += (couldBuyThisDay + 1) * (nbAdditionDays + 1);
    // console.log("result", result);
    couldBuyOnPreviousDay = couldBuyThisDay + 1;
    day += nbAdditionDays + 1;
  }

  console.log(result);
}

parseInput();

testCases.forEach(solution);

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 L = process.env.DEBUG ? console.log : ()=>{};

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

const calc = (n, x, A)=>{
  A.sort((a, b)=>a-b);
  let l=0, sum = 0, ans = 0;
  for (; l<n; l++){
    if (sum+A[l]<=x)
      sum += A[l];
    else
     break
  }
  let add = 1;
  ans += l;
  if (sum==0)
    return 0;
    let cnt = 0
  while (l>0){
cnt++
    sum += l;
    while (sum>x){ // optimize
      sum -= A[l-1]+add;
      l--;
    }
    if (l==0)
      break;
    // find max i, so sum+i*l=x
    let i = Math.floor((x-sum+l)/l);
    if (i>0){
      ans += l*i;
      add += i;
      sum += l*(i-1);
    }
  }
  //L({x,n,A, l, sum, ans, cnt})
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let [n, x] = ra();
      let a = ra();
      L('Ans:')
      print(calc(n, x, a));
    }
}

E.calc = calc;

"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 [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    arr.sort((a, b) => a - b);
    let sum = arr.reduce((acc, cur) => acc + cur, 0);
    let j = n - 1,
      days = 0,
      pack = 0,
      len = 0,
      s1 = sum;
    while (j >= 0) {
      if (s1 <= k) {
        days = Math.floor((k - s1) / (j + 1)) + 1;
        pack += days * (j + 1);
        len += days;
      }
      sum -= arr[j--];
      s1 = sum + (j + 1) * len;
    }
    console.log(pack);
  }
};
solve();

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) {
    arr.sort((a, b) => a - b)
    //
    let now = 0
    let ans = 0
    for (let i = 0; i < arr.length; i++) {
        const s = (arr[i])
        now += s
        //
        if (k < now) break

        const c = (i + 1)
        const d = binarySearch(1, 1e9, x => {
            return now + (x - 1) * c <= k
        })
        // console.log(i, d, now)
        ans += d
    }
    return ans
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        // const m = ((l + r) / 2n)
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

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

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

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

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const calc = (n, x, a)=>{
    a = a.sort((a0, a1) => a0 - a1);
    let count = 0;
    let sum = 0;

    for (let i = 0; i < n; i++) {
        if (a[i] > x) break;

        sum += a[i];

        if (sum > x) break;

        let num = i + 1;
        let localSum = 0;

        const check = (d) => {
            let seq = d - 1;
            // let seq = d % 2 === 0
            //     ? Math.round((d / 2) * (d + 1))
            //     : Math.round(((d + 1) / 2) * d);
            seq *= num;
            return seq + sum <= x;
        }

        let l = 1, r = x;
        while (l < r) {
            // console.log(`DEBUG l ${l} r ${r}`);
            let mid = l + Math.ceil((r - l) / 2);
            if (check(mid)) {
                l = mid;
            } else {
                r = mid - 1;
            }
        }
        // console.log(`DEBUG l ${l} r ${r}`);
        count += (l * num);
        count -= (l * (num - 1));
    }

    return count;
};

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

'use strict';

var readline = require('readline');

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

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

function solve(n, x, a) {
  a.sort((x, y) => x - y);
  const sum = [];
  for (let i = 0; i < n; i++) {
    var _sum;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + a[i];
  }
  let res = 0,
      day = 0;
  for (let i = n - 1; i >= 0; i--) {
    let num = Math.max(Math.floor((x - sum[i]) / (i + 1)) + 1, 0);
    res += (i + 1) * (num - day);
    day = num;
  }
  console.log(res);
}

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

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

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 L = process.env.DEBUG ? console.log : ()=>{};

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

const calc = (n, x, A)=>{
  A.sort((a, b)=>a-b);
  let l=0, sum = 0, ans = 0;
  for (; l<n; l++){
    if (sum+A[l]<=x)
      sum += A[l];
    else
     break
  }
  let add = 1;
  ans += l;
  if (sum==0)
    return 0;
    let cnt = 0
  while (l>0){
cnt++
    sum += l;
    if (sum>x){ // optimize
      sum -= A[l-1]+add;
      l--;
    }
    if (l==0)
      break;
    // find max i, so sum+i*l=x
    let i = Math.floor((x-sum+l)/l);
    if (i>0){
      ans += l*i;
      add += i;
      sum += l*(i-1);
    }
  }
  //L({x,n,A, l, sum, ans, cnt})
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let [n, x] = ra();
      let a = ra();
      L('Ans:')
      print(calc(n, x, a));
    }
}

E.calc = calc;


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

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

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

		let ans = 0;
		const has = Array(n).fill(0);
		for (let i = 0; i < n; i++) {
			const need = Math.max(0, (s[i]-1)-has[i]);
			ans += need;

			has[i] = Math.max(s[i]-1, has[i]);
			has[i+1] += has[i]-(s[i]-1);
			for (let j = i+2; j < Math.min(s[i]+i+1, n); j++) {
				has[j]++;
			}
		}

		console.log(ans);
	}
}

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

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

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

		let ans = 0;
		const cur = Array(n).fill(0);
		for (let i = 0; i < n; i++) {
			let need = Math.max(0, s[i]-1-cur[i]);
			ans += need;

			for (let j = i + 2; j <= Math.min(i + s[i], n-1); j++) {
				cur[j]++;
			}

			let have = Math.max(s[i]-1, cur[i]);
			cur[i+1] += have - (s[i]-1);
		}

		console.log(ans);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })

        var ans = 0
        var count = new Array(n).fill(0)
        for (let i = 0; i < n; i++) {
            var current = a[i] - 1

            if (a[i] > Math.max(n - i - 1, 1)) {
                var d = a[i] - Math.max(n - i - 1, 1)
                a[i] -= d
            }

            for (var j = a[i]; j >= 2; j--) {
                count[j + i]++
            }

            ans += Math.max(current - count[i], 0)
            if (i < (n - 1) && count[i] > current) {
                count[i + 1] += count[i] - current
            }
            // console.log(ans, current - count[i])
            // console.log(count)
        }
        console.log(ans)
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })

        var ans = 0
        var count = new Array(n).fill(0)
        for (let i = 0; i < n; i++) {
            var current = a[i] - 1

            if (a[i] > Math.max(n - i - 1, 1)) {
                var d = a[i] - Math.max(n - i - 1, 1)
                a[i] -= d
            }

            for (var j = a[i]; j >= 2; j--) {
                count[j + i]++
            }

            ans += Math.max(current - count[i], 0)
            if (j < n - 1 && count[i] > a[i]) {
                count[i + 1] += count[i] - a[i]
            }
            // console.log(ans, current - count[i])
            // console.log(count)
        }
        console.log(ans)
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var ans = 0
        var count = new Array(n).fill(0)
        for (let i = 0; i < n; i++) {
            var current = a[i] - 1

            if (a[i] > Math.max(n - i - 1, 1)) {
                var d = a[i] - Math.max(n - i - 1, 1)
                a[i] -= d
            }

            for (var j = a[i]; j >= 2; j--) {
                count[j + i]++
            }

            ans += Math.max(current - count[i], 0)
        }
        console.log(ans)
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0
        var temp = new Array(n).fill(0)
        for (let i = 0; i < n; i++) {
            var current = temp[i]

            if (a[i] > Math.max(current, 1)) {
                count += a[i] - temp[i] - 1
                current = a[i] - temp[i] - 1
            }
            // console.log(current)

            for (let j = i + 2; j < n && j < i + a[i]+1; j++) {
                temp[j]++
            }
            // console.log(temp)
            // console.log(a)
        }
        console.log(count)
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0
        var temp = new Array(n).fill(0)
        for (let i = 0; i < n; i++) {
            var current = temp[i]

            if (a[i] > Math.max(current, 1)) {
                count += a[i] - temp[i] - 1
                current = a[i] - temp[i] - 1
            }
            // console.log(current)

            for (let j = i + 2; j < n && j < i + 2 + current; j++) {
                temp[j]++
            }
            // console.log(temp)
            // console.log(a)
        }
        console.log(count)
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0
        var next = 0
        var nextI = 0

        while (exist) {
            exist = false
            for (let i = nextI; i < n; i++) {
                // console.log(a, count)
                // console.log(a)
                // console.log(i)
                if (a[i] + i < n && a[i] !== 1) {
                    nextI = i
                    exist = true
                    // var j = i
                    for (let jj = i + 1; jj < n; jj++) {
                        var dd = Math.floor(Math.log2(jj - i))
                        dd = Math.min(dd, a[i]-1)
                        // console.log(jj, jj - i, dd)
                        a[jj] = Math.max(1, a[jj] - dd)
                    }
                    count += a[i] - 1
                    a[i] = 1
                    break
                } else {
                    if (a[i] !== 1 && (a[i] + i) >= n) {
                        nextI = i

                        // console.log(i, a[i], a[i] + i - n + 1)
                        var dif = Math.min(a[i] + i - n + 1, a[i] - 1)
                        a[i] = a[i] - dif
                        count = count + dif
                        exist = true
                        break
                    }
                }
            }
        }
        // console.log(a)

        // for (let i = 0; i < n; i++) {
        //     if (a[i] > 1) count = count + BigInt(a[i]) - 1n
        // }
        console.log(count.toString())
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0
        var next = 0
        var nextI = 0

        while (exist) {
            exist = false
            for (let i = nextI; i < n; i++) {
                // console.log(a)
                // console.log(i)
                if (a[i] + i < n && a[i] !== 1) {
                    nextI = i
                    count++
                    exist = true
                    var j = i
                    while (j < n) {
                        next = a[j] + j
                        if (a[j] === 1) a[j] = 1
                        else a[j]--
                        j = next
                    }
                    break
                } else {
                    if (a[i] !== 1 && (a[i] + i) >= n) {
                        nextI = i
                        for (let jj = i + 1; jj < n; jj++) {
                            var dd = Math.floor((jj - i) / 2)
                            a[jj] = Math.max(1, a[jj] - dd)
                        }
                        var dif = Math.min(a[i] + i - n + 1, a[i] - 1)
                        a[i] = a[i] - dif
                        count = count + dif
                        exist = true
                        break
                    }
                }
            }
        }
        // console.log(a)

        // for (let i = 0; i < n; i++) {
        //     if (a[i] > 1) count = count + BigInt(a[i]) - 1n
        // }
        console.log(count.toString())
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0n
        var next = 0

        while (exist) {
            exist = false
            for (let i = 0; i < n; i++) {
                if (a[i] + i < n && a[i] !== 1) {
                    count++
                    exist = true
                    var j = i
                    while (j < n) {
                        next = a[j] + j
                        if (a[j] === 1) a[j] = 1
                        else a[j]--
                        j = next
                    }
                    // console.log(a)
                    break
                }
            }
        }

        for (let i = 0; i < n; i++) {
            if (a[i] > 1) count = count + BigInt(a[i]) - 1n
        }
        console.log(count.toString())
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0n

        while (exist) {
            exist = false
            for (let i = 0; i < n; i++) {
                if (a[i] + i < n && a[i] !== 1) {
                    count++
                    exist = true
                    var j = i
                    while (j < n) {

                        if (a[j] === 1) a[j] = 1
                        else a[j]--
                        j = a[j] + j
                    }
                }
            }
        }

        for (let i = 0; i < n; i++) {
            if (a[i] > 1) count = count + BigInt(a[i]) - 1n
        }
        console.log(count.toString())
        // console.log(a)

    })
}

'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 = 1000000000n + 7n
var maxN = 1002

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

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        var exist = true
        var count = 0

        while (exist) {
            exist = false
            for (let i = 0; i < n; i++) {
                if (a[i] + i < n && a[i] !== 1) {
                    count++
                    exist = true
                    var j = i
                    while (j < n) {

                        if (a[j] === 1) a[j] = 1
                        else a[j]--
                        j = a[j] + j
                    }
                }
            }
        }

        for (let i = 0; i < n; i++) {
            if (a[i] > 1) count += a[i] - 1
        }
        console.log(count)
        // console.log(a)

    })
}


var n = parseInt(readline());
var a = new Array(n)
if(n <= 2)print("1\n1")
else if(n == 3)print("2\n1 3")
else {
  for (var i=0;i<n;i++){
    if(i<(n-n%2)/2)a[i]=(i+1)*2
    else a[i]=2*(i-(n-n%2)/2)+1
  }
  var res=""
  for(var i=0;i<n;i++){
     res+=a[i]
     if(i!=n-1)res+=" "
  }
  print(a.length)
  print(res)
}

var n = readline();
var a = new Array(n)
if(n <= 2)print("1\n1")
else if(n == 3)print("2\n1 3")
else {
  for (var i=0;i<n;i++){
    if(i<(n-n%2)/2)a[i]=(i+1)*2
    else a[i]=2*(i-(n-n%2)/2)+1
  }
  var res=""
  for(var i=0;i<n;i++){
     res+=a[i]
     if(i!=n-1)res+=" "
  }
  print(a.length)
  print(res)
}

var n = +readline(), a = [];
for(i = 1; i <= n; i++){
	a[i] = i;
}
var buf, first, last;

if(n == 1){
	write(n + "\n");
	write(1);
}
else if(n == 2){
	write(1 + "\n");
	write(1);
}
else if(n == 3){
	write(2 + "\n");
	write(1 + " " + 3);
}
else{
	if(n % 2 == 0){
		first = 2;
		last = n-1;

		for(var i = 0; i < ((n-2)/2); first++, last--, i++){
			for(var j = first, k = (n/2 + 1); ; j++, k++){
				buf = a[k];
				a[k] = a[j];
				a[j] = buf;

				if(k == last){
					break;
				}
			}
		}

		a.splice(0,1);
		write(n + "\n");
		write(a.join(" "));
	}
	else{
		first = 2;
		last = n-1;

		for(var i = 0; i < ((n-3)/2); first++, last--, i++){
			for(var j = first, k = (Math.ceil(n/2) + 1); ; j++, k++){
				buf = a[k];
				a[k] = a[j];
				a[j] = buf;

				if(k == last){
					break;
				}
			}
		}

		a.splice(Math.ceil(n/2), 1);
		a.splice(0, 1);
		write((n-1) + "\n");
		write(a.join(" "));
	}
}

var n = +readline(), a = [];
for(i = 1; i <= n; i++){
	a[i] = i;
}
var buf, first, last;

if(n == 1){
	write(n + "\n");
	write(1);
}
else if(n == 2){
	write(0 + "\n");
	write("");
}
else if(n == 3){
	write(2 + "\n");
	write(1 + " " + 3);
}
else{
	if(n % 2 == 0){
		first = 2;
		last = n-1;

		for(var i = 0; i < ((n-2)/2); first++, last--, i++){
			for(var j = first, k = (n/2 + 1); ; j++, k++){
				buf = a[k];
				a[k] = a[j];
				a[j] = buf;

				if(k == last){
					break;
				}
			}
		}

		a.splice(0,1);
		write(n + "\n");
		write(a.join(" "));
	}
	else{
		first = 2;
		last = n-1;

		for(var i = 0; i < ((n-3)/2); first++, last--, i++){
			for(var j = first, k = (Math.ceil(n/2) + 1); ; j++, k++){
				buf = a[k];
				a[k] = a[j];
				a[j] = buf;

				if(k == last){
					break;
				}
			}
		}

		a.splice(Math.ceil(n/2), 1);
		a.splice(0, 1);
		write((n-1) + "\n");
		write(a.join(" "));
	}
}

var n = parseInt(readline());
var a = new Array(n)
if(n == 1)print("1\n1")
else if(n == 2)print("0")
else if(n == 3)print("2\n1 3")
else {
  for (var i=0;i<n;i++){
    if(i<(n-n%2)/2)a[i]=(i+1)*2
    else a[i]=2*(i-(n-n%2)/2)+1
  }
  var res=""
  for(var i=0;i<n;i++){
     res+=a[i]
     if(i!=n-1)res+=" "
  }
  print(a.length)
  print(res)
}

var n = readline();
var a = new Array(n)
if(n == 1)print("1\n1")
else if(n == 2)print("0")
else if(n == 3)print("2\n1 3")
else {
  for (var i=0;i<n;i++){
    if(i<(n-n%2)/2)a[i]=(i+1)*2
    else a[i]=2*(i-(n-n%2)/2)+1
  }
  var res=""
  for(var i=0;i<n;i++){
     res+=a[i]
     if(i!=n-1)res+=" "
  }
  print(res)
}

var n = readline();
var a = new Array(n)
if(n == 1)print("1\n1")
else if(n == 2)print("0")
else if(n == 3)print("2\n1 3")
else {
  for (var i=0;i<n;i++){
    if(i<(n-n%2)/2)a[i]=(i+1)*2
    else a[i]=2*(i-(n-n%2)/2)+1
  }
  var res=""
  for(var i=0;i<n;i++){
     res+=a[i]
     if(i!=n-1)res+=" "
  }
  print(a.length)
  print(res)
}

var n = readline();
var a = new Array(n)
if(n <= 1)print("1\n1")
else if(n == 3)print("2\n1 3")
else {
  for (var i=0;i<n;i++){
    if(i<(n-n%2)/2)a[i]=(i+1)*2
    else a[i]=2*(i-(n-n%2)/2)+1
  }
  var res=""
  for(var i=0;i<n;i++){
     res+=a[i]
     if(i!=n-1)res+=" "
  }
  print(a.length)
  print(res)
}


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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			break;
		}
	}
	i = i - p;

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = 1; //parseInt(lines[0]);
    var l = 0;
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].split(' ').map(Number)
        var str = lines[l++]
        console.log(solve(n, k, str));
    }
});

function solve(n, k, str) {
    if (n > k) return solve(k, k, str.slice(0, k))

    let min
    for (var i = 0; i < n; i++) {
        const after = fill(str.slice(0, n - i), k)
        if (!min || after < min) {
            min = after
        }
        // console.log(after, min)
    }
    return min

    // str = min
    // // console.log('1', str)
    // let end = -1
    // for (var i = str.length - 1; i >= 0; i--) {
    //     if (str[i] === str[0]) {
    //         // skip
    //     } else {
    //         end = i
    //         break
    //     }
    // }
    // if (end >= 0) {
    //     str = str.slice(0, end + 1)
    // }
    // console.log('2', str)

    // return fill(str, k)
}

function fill(min, k) {
    let r = min
    while (r.length < k) {
        r += min
    }
    return r.slice(0, k)
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    const output = function(l) {
        for(let i = 0; i<k; i++) {
            rl.output.write(s.charAt(i%l));
        }
    }
    for(let i = 1; i < s.length && i < k; i++) {
        let j;
        for(j = 0; i + j < s.length && s.charAt(j) === s.charAt(i+j); j++);
        if (i + j < s.length && s.charAt(j) < s.charAt(i + j) || i + j >= s.length){
            output(i);
            return;
        }
    }
    output(s.length);

}

solve();

function solve() {
   var nk = readArray(Number);
   var n = nk[0];
   var k = nk[1];
   var str = read();
   var current = 1;
   var savepoint;
   var check;
   while(true) {
      if (current >= n) {
         break;
      }
      if (str[current] > str[0]) {
         str = str.substr(0, current);
         break;
      }
      if (str[current] < str[check]) {
         current++;
         continue;
      }
      savepoint = current;
      check = 0;
      while (current < 3 * n && str[current % n] === str[check]) {
         current++;
         check++;
         if (check >= savepoint) {
            check = 0;
         }
      }
      if (current !== 3 * n && str[current % n] > str[check]) {
         str = str.substr(0, savepoint);
         break;
      }
   }
   while(str.length < k) {
      str = str + str;
   }
   write(str.substr(0, k));
}

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

function init() {
   try {
      var T;
      T = 1;
      //T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			i = i - p;
			break;
		}
	}

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			break;
		}
	}

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 0;
	while (i < s.length && s[i] <= s[0]) i++;

	s = s.slice(0, i).repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    const output = function(l) {
        for(let i = 0; i<k; i++) {
            rl.output.write(s.charAt(i%l));
        }
    }
    for(let i = 1; i < s.length && i < k; i++) {
        let j;
        for(j = 0; i + j < s.length && s.charAt(j) === s.charAt(i+j); j++);
        if (i + j < s.length && s.charAt(j) < s.charAt(i + j)){
            output(i);
            return;
        }
    }
    output(s.length);

}

solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    const output = function(l) {
        for(let i = 0; i<k; i++) {
            rl.output.write(s[i%l]);
        }
    }
    for(let i = 1; i < s.length && i < k; i++) {
        let j;
        for(j = 0; i + j < s.length && s[j] === [i+j]; j++);
        if (i + j < s.length && s[j] < s[i + j]){
            output(i);
            return;
        }
    }
    output(Math.min(s.length,k));

}

solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    if (s.length >= k) {
        console.log(s.substr(0, k))
        return;
    } else {
        const output = function(l) {
            for(let i = 0; i<k; i++) {
                rl.output.write(s[i%l]);
            }
        }
        for(let i = 1; i < s.length; i++) {
            let j;
            for(j = 0; i + j < s.length && s[j] === [i+j]; j++);
            if (i + j < s.length && s[j] < s[i + j]){
                output(i);
                return;
            }
        }
        output(s.length);
    }

}

solve();

var matr = 'haha';

function create(str) {
   var hahaIndexArr = [];
   for (var i = 0; i < str.length; i++) {
      var hasWrong = false;
      for (var j = 0; j < matr.length; j++) {
         if (str[i + j] !== matr[j]) {
            hasWrong = true;
            break;
         }
      }
      if (!hasWrong) {
         hahaIndexArr.push(i);
      }
   }
   if (hahaIndexArr.length === 0) {
      if (str.length < 8) {
         return [str, -1, str];
      }
      return [str.substr(0, 4), 0, str.substr(str.length - 4, 0)];
   }
   var preff = str.substr(0, Math.min(4, hahaIndexArr[0])) || 'ha';
   var suff = str.substr(Math.max(hahaIndexArr[hahaIndexArr.length - 1] + 4, str.length - 4)) || 'ha';
   return [preff, hahaIndexArr.length, suff];
}
function summ(a, b) {
   var createMiddle = create(a[2] + b[0]);
   if (a[1] === -1 && b[1] === -1) {
      return createMiddle;
   }
   var preff = a[1] === -1 ? createMiddle[0] : a[0];
   var suff = b[1] === -1 ? createMiddle[2] : b[2];
   var asum = a[1] === -1 ? 0 : a[1];
   var bsum = b[1] === -1 ? 0 : b[1];
   var midSum = createMiddle[1] === -1 ? 0 : createMiddle[1];
   return [preff, asum + bsum + midSum, suff];
}

function solve() {
   var nk = readArray(Number);
   var n = nk[0];
   var k = nk[1];
   var str = read();
   var current = 1;
   var savepoint;
   var check;
   while(true) {
      if (current >= n) {
         break;
      }
      if (str[current] > str[0]) {
         str = str.substr(0, current);
         break;
      }
      if (str[current] < str[check]) {
         current++;
         continue;
      }
      savepoint = current;
      check = 0;
      while (current < n && str[current] === str[check]) {
         current++;
         check++;
         if (check >= savepoint) {
            check = 0;
         }
      }
      if (current !== n && str[current] > str[check]) {
         str = str.substr(0, savepoint);
         break;
      }
   }
   while(str.length < k) {
      str = str + str;
   }
   write(str.substr(0, k));

}

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

function init() {
   try {
      var T;
      T = 1;
      //T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = 1; //parseInt(lines[0]);
    var l = 0;
    for (var i = 0; i < t; i++) {
        var [n, k] = lines[l++].split(' ').map(Number)
        var str = lines[l++]
        console.log(solve(n, k, str));
    }
});

function solve(n, k, str) {
    if (n > k) return solve(k, k, str.slice(0, k))

    let min
    for (var i = 0; i < n; i++) {
        const after = fill(str.slice(0, n - i), n)
        if (!min || after < min) {
            min = after
        }
    }

    return fill(min, k)
}

function fill(min, k) {
    let r = min
    while (r.length < k) {
        r += min
    }
    return r.slice(0, k)
}


var main = function () {
    var n = parseInt(readline());
    var p = [];
    readline().split(/\s+/).forEach(function (t) {
        p.push(parseFloat(t));
    });

    p.sort();

    if (p[p.length - 1] === 1) {
        print(1);
        return;
    }

    var addP = function (cur, pr, v) {
        return cur + v * pr / (1 - v)
    }

    var ans = 0;

    for (var pref = 0; pref <= p.length; ++pref) {
        for (var suff = 0; pref + suff <= p.length; suff++) {
            var cur = 0;
            var pr = 1;

            for (var i = 0; i < pref; ++i)
                pr *= 1 - p[i];
            for (var i = p.length - suff; i < p.length; ++i)
                pr *= 1 - p[i];

            for (var i = 0; i < pref; ++i)
                cur = addP(cur, pr, p[i]);
            for (var i = p.length - suff; i < p.length; ++i)
                cur = addP(cur, pr, p[i]);

            ans = Math.max(ans, cur);
        }
    }

    print(ans);
};

main();

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

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

function tokenizeFloats(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseFloat(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		probs = tokenizeFloats(readline());
	probs.sort(function (a, b) {
		return a - b;
	});
	var best = 0.0;
	for (var i = n-1; i >= 0; --i) {
		var total = 0.0;
		for (var j = i; j < n; ++j) {
			var p = 1.0;
			for (var k = i; k < n; ++k) {
				if (k == j) {
					p *= probs[k];
				} else {
					p *= (1-probs[k]);
				}
			}
			total += p;
		}
		best = Math.max(best, total);
	}
	print(best);
}

main();

var main = function () {
    var n = parseInt(readline());
    var p = [];
    readline().split(/\s+/).forEach(function (t) {
        p.push(parseFloat(t));
    });

    p.sort();

    var addP = function (cur, pr, v) {
        return cur + v * pr / (1 - v)
    }

    var ans = 0;

    for (var pref = 0; pref <= p.length; ++pref) {
        for (var suff = 0; pref + suff <= p.length; suff++) {
            var cur = 0;
            var pr = 1;

            for (var i = 0; i < pref; ++i)
                pr *= 1 - p[i];
            for (var i = p.length - suff; i < p.length; ++i)
                pr *= 1 - p[i];

            for (var i = 0; i < pref; ++i)
                cur = addP(cur, pr, p[i]);
            for (var i = p.length - suff; i < p.length; ++i)
                cur = addP(cur, pr, p[i]);

            ans = Math.max(ans, cur);
        }
    }

    print(ans);
};

main();


var tests = parseInt(readline());
    var n;
    var arr;
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        arr = readline().split(' ').map(x=>parseInt(x));
        var set = new Set();
        var index = 0;
        for (var i = n-1; i >= 0; i--) {
            if (set.has(arr[i])) {
                index = i+1;
                break;
            }
            set.add(arr[i]);
        }
        print(index);
    }

var t = readline().split(" ").map((x) => parseInt(x));
for(var i = 0; i < t ; i++) {
  var n = readline().split(" ").map((x) => parseInt(x));
  var nums = readline().split(" ").map((x) => parseInt(x));
  var dict = {};
  var move = 0;

  nums.map((item, key) => {
    if(dict[item] !== undefined) {
      move = Math.max(dict[item] + 1, move);
    }
    dict[item] = key;
  })
  print(move);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var caseMap = new Map();
    var sequence = 0;
    for (var j = caseLength-1; j >= 0; j--)
    {
        if (caseMap.has(caseArray[j]))
        {
            break;
        }
        else
        {
            sequence++;
            caseMap.set(caseArray[j], 1);
        }
    }
    print(caseLength-sequence);
}

var t = readline();
for(var i=0;i<t;i++){
    var n = readline();
    var arr = readline().split(' ').map(x=>parseInt(x));
    var map={};
    var ans=0;
    for(var j=arr.length;j>=0;j--){
        if(map[arr[j]]){
            ans=j+1;
            break;
        }
        else{
            map[arr[j]]=1;
        }
    }
    print(ans);
}

var t = +readline();

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

      var nums = [];
    var t1 = +readline();
    var list = readline().split(' ').map((t) => +t);
    print(removePrefix(list));

}

function removePrefix(arr){

  var set = new Set();
  for(var i = arr.length; i>=0; i--){
    if (set.has(arr[i])){
      return i + 1
    }
    set.add(arr[i])
  }

  return 0;

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        var w = false;
        for (let j = a.length - 1; j >= 0; j--) {
            if (!A[a[j]]) {
                A[a[j]] = true;
            } else {
                console.log(j + 1);
                w = true;
                break;
            }
        }
        if (!w) {
            console.log(0);
        }
    }
}

function solve() {
  const n = Number(cl());
  const arr = cl().split(' ').map((item) => Number(item));

  const set = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (set.has(arr[i])) {
      return co(i + 1);
    }
    set.add(arr[i]);
  }
  co(0);
}

function Solution() {
  let n = Number(cl());
  while (n--) solve();
}

let i = 0;
const lines = []

function cl() { return lines[i++] }
function co(str) { console.log(str)}
const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', (input) => lines.push(input));
rl.on('close', Solution);

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
});
function readline() {
    return inputString[currentLine++];
}
function output(x) {
    if (typeof x !== 'string')
    {
        x = x.toString();
    }
    console.log(x);
}

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

    for (let test = 0; test < N; test++)
    {
        const n = Number(readline());
        const arr = readline().split(' ').map(Number);
        const hash = {};
        for (let i = arr.length - 1; i >= 0; i--)
        {
            if (hash[arr[i]])
            {
                output(i + 1);
                break;
            }
            else
            {
                hash[arr[i]] = true;
            }
            if (i === 0)
            {
                output(0);
            }
        }
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        const n = +readLine();
        const arr= readLine().split(' ').map(p => +p);
        let result = myFunc(n, arr);
        console.log(result);
    }
}

function myFunc(n, arr){
    let map = [];
    let resp = 0;

    for(let i = n-1; i >=0; i--){
        if(map[arr[i]] != undefined){
            break;
        }
        else{
            map[arr[i]] = 1;
            resp++;
        }
    }

    return n-resp;
}

// cls; cat .\input.txt | node .\script.js
// codium --diff file1.js file2.js
'use strict';
let data = ''; // raw
let inputs = ''; // iterator
function read() { return inputs.next().value.trim(); };

async function solve() {
    let length = parseInt(await read())
    let value = (await read()).split(' ').map(Number)
    let counter = 0
    let map = {}
    for (let i = value.length - 1; i >= 0; i--) {
        const element = value[i];
        if (element in map) {
            break
        } else {
            map[element] = true
            counter++
        }
    }
    return length - counter
}

async function main() {
    let tasks_amount = parseInt(await read())
    for (let i = 0; i < tasks_amount; i++) {
        let result = await solve()
        console.log(result)
    }
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    let splitted = data.split('\r\n')
    inputs = await splitted.values();
    await main();
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        const n = Number(readline());
        const arr = readline().split(' ').map(Number);
        const hash = {};
        for (let i = arr.length - 1; i >= 0; i--) {
            if (hash[arr[i]]) {
                output(i + 1);
                break;
            } else {
                hash[arr[i]] = true;
            }
            if (i === 0) {
                output(0);
            }
        }
    }
}

'use strict';

function solve(n, a) {
  const set = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (set.has(a[i])) return i + 1;
    set.add(a[i]);
  }
  return 0;
}

async function main(r) {
  const rn = async () => Number(await r());
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  try {
    let t = Number(await r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = await rn();
      const a = await rns();
      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);
});

const readline = require('readline')

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

function solve(n, arr) {
    const m = {}
    for (let i = arr.length - 1; i >= 0; i--) {
        const x = arr[i]
        if (m[x]) {
            return i + 1
        }
        m[x] = 1
    }
    return 0
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var set = new Set();
		var output = N;
		for(var i = N - 1; i >= 0; i--){
			if(!set.has(list[i])){
				set.add(list[i]);
				output--;
			}else{
				break;
			}
		}
		myout(output);
	}
}

var t = readline().split(" ").map((x) => parseInt(x));
for(var i = 0; i < t ; i++) {
  var n = readline().split(" ").map((x) => parseInt(x));
  var nums = readline().split(" ").map((x) => parseInt(x));
  var dict = {};
  var move = 0;

  nums.map((item, key) => {
    if(dict[item] !== undefined) {
      move = dict[item] + 1;
    }
    dict[item] = key;
  })
  print(move);
}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (!A[a[j]]) {
                A[a[j]] = true;
            } else {
                d = a.length - Object.keys(A).length;
                break;
            }
            if (n === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (A[a[j]]) {
                d = j + 1;
                break;
            } else {
                A[a[j]] = true;
            }
            if (n === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
/**
 * План подзадачи:
 * - создаем пустой обьект А
 * - идем по элементам с конца массива
 *   - проверяем есть ли элемент в объекте А
 *   - если элемента нет, то добавляем в объект А свойство значение элемента
 *   - если элемент есть , то мы останавливаем итерацию и выводим в качестве ответа длину всего массива минус число пройденных элементов
 * - если мы еще не вышли, то ответ 0
 */

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (A[a[j]]) {
                d = i + 1;
                break;
            } else {
                A[a[j]] = true;
            }
            if (j === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (A[a[j]]) {
                d = i + 1;
                break;
            } else {
                A[a[j]] = true;
            }
            if (j === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}