function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let d = Arr(1, n - 1, 1, i => a[i] - a[i - 1]);
  let a0 = a[0];
  let k = d.map(v => v > 0 ? v : 0).sum();
  out.push(Math.ceil((a0 + k) / 2) + 0);
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(d[l - 1], 0);
      d[l - 1] += x;
      k += max(d[l - 1], 0);
    }
    if (r < n) {
      k -= max(d[r], 0);
      d[r] -= x;
      k += max(d[r], 0);
    }
    out.push(Math.ceil((a0 + k) / 2) + 0);
  }
  log(out.join('\n'))
}

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    let negSum = 0;
    let posSum = 0;
    if(n === 1){
        if(a[0] % 2 === 0)
            console.log(a[0]/2);
        else
            console.log(Math.ceil(a[0]/2));

        let q = pi(readline());
        while(q > 0){
            q--;
            let [l,r,x] = ti(readline().split(' '));
            a[0] += x;

            if(a[0] % 2 === 0){
                let res = a[0]/2;
                console.log(res === -0 ? 0 : res);
            }
            else{
                let res = Math.ceil(a[0]/2);
                console.log(res === -0 ? 0 : res);
            }
        }

        return;
    }

    let max = 0;
    let d = new Array(n);
    for(let i = 1; i < n; i++){
        d[i-1] = a[i] - a[i-1];
        max += Math.max(0, d[i-1]);
    }

    console.log(Math.ceil((a[0] + max) / 2));
    let q = pi(readline());
    while(q > 0){
        q--;
        let [l, r, x] = ti(readline().split(' '));

        if(l-1 !== 0){
            if(d[l-2] > 0)
                max -= d[l-2];
            d[l-2] += x;
            if(d[l-2] > 0)
                max += d[l-2];
        }else{
            a[l-1] += x;
        }

        if(r < n){
            if(d[r-1] > 0)
                max -= d[r-1];
            d[r-1] += -x;
            if(d[r-1] > 0)
                max += d[r-1];
        }

        console.log(Math.ceil((a[0] + max) / 2));
    }
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let d = Arr(1, n - 1, 1, i => a[i] - a[i - 1]);
  let a0 = a[0];
  let k = d.map(v => v > 0 ? v : 0).sum();
  out.push(Math.ceil((a0 + k) / 2) + '');
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(d[l - 1], 0);
      d[l - 1] += x;
      k += max(d[l - 1], 0);
    }
    if (r < n) {
      k -= max(d[r], 0);
      d[r] -= x;
      k += max(d[r], 0);
    }
    out.push(Math.ceil((a0 + k) / 2) + '');
  }
  log(out.join('\n'))
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let d = Arr(1, n - 1, 1, i => a[i] - a[i - 1]);
  let a0 = a[0];
  let k = d.map(v => v > 0 ? v : 0).sum();
  log(Math.ceil((a0 + k) / 2) + '');
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(d[l - 1], 0);
      d[l - 1] += x;
      k += max(d[l - 1], 0);
    }
    if (r < n) {
      k -= max(d[r], 0);
      d[r] -= x;
      k += max(d[r], 0);
    }
    log(Math.ceil((a0 + k) / 2) + '');
  }
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let a0 = a[0];
  let k = Arr(1, n - 1, 1, i => max(a[i] - a[i - 1], 0)).sum();
  log(Math.ceil((a0 + k) / 2));
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(a[l - 1] - a[l - 2], 0);
      k += max(a[l - 1] + x - a[l - 2], 0);
    }
    if (r < n) {
      k -= max(a[r] - a[r - 1], 0);
      k += max(a[r] - a[r - 1] - x, 0);
    }
    log(Math.ceil((a0 + k) / 2));
  }
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let d = Arr(1, n - 1, 1, i => a[i] - a[i - 1]);
  let a0 = a[0];
  let k = d.map(v => v > 0 ? v : 0).sum();
  out.push((a0 + k) / 2 | 0);
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(d[l - 1], 0);
      d[l - 1] += x;
      k += max(d[l - 1], 0);
    }
    if (r < n) {
      k -= max(d[r], 0);
      d[r] -= x;
      k += max(d[r], 0);
    }
    out.push((a0 + k) / 2 | 0);
  }
  log(out.join('\n'))
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let d = Arr(1, n - 1, 1, i => a[i] - a[i - 1]);
  let a0 = a[0];
  let k = d.map(v => v > 0 ? v : 0).sum();
  let kq = a0 + k;
  out.push((kq + (kq > 0)) / 2 | 0);
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(d[l - 1], 0);
      d[l - 1] += x;
      k += max(d[l - 1], 0);
    }
    if (r < n) {
      k -= max(d[r], 0);
      d[r] -= x;
      k += max(d[r], 0);
    }
    kq = a0 + k;
    out.push((kq + (kq > 0)) / 2 | 0);
  }
  log(out.join('\n'))
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let a0 = a[0];
  let k = Arr(1, n - 1, 1, i => max(a[i] - a[i - 1], 0)).sum();
  log(Math.ceil((a0 + k) / 2) + '');
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(a[l - 1] - a[l - 2], 0);
      k += max(a[l - 1] + x - a[l - 2], 0);
    }
    if (r < n) {
      k -= max(a[r] - a[r - 1], 0);
      k += max(a[r] - a[r - 1] - x, 0);
    }
    log(Math.ceil((a0 + k) / 2) + '');
  }
}

function For(a, b, step, fn) {
  let res;
  if (step > 0) {
    for (let i = a; i <= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  } else {
    for (let i = a; i >= b; i += step) {
      if ((res = fn(i)) != null) return res;
    }
  }
}

function Arr(a, b, step, fn, init) {
  if (!step) {
    return a < b
      ? Array(b - a + 1).fill(0).map((v, i) => fn(a + i))
      : Array(a - b + 1).fill(0).map((v, i) => fn(a - i))
  }
  let arr = Array(Math.max(a, b) + 1).fill(0);
  if (init) init(arr);
  if (step > 0) for (let i = a; i <= b; i += step) arr[i] = fn(i, arr);
  else for (let i = a; i >= b; i += step) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == min : v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex((v, i) => fn ? fn(v, i) == max : v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(0, n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(0, n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => {
//   return gt[n] * rgt[k] * rgt[n - k] % MOD;
// }
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let n = $()
  let a = $(n)
  let d = Arr(1, n - 1, 1, i => a[i] - a[i - 1]);
  let a0 = a[0];
  let k = d.map(v => v > 0 ? v : 0).sum();
  out.push((a0 + k + (a0 + k > 0)) / 2 | 0);
  let q = $()
  while (q--) {
    let [l, r, x] = $(3)
    if (l == 1) a0 += x;
    else {
      k -= max(d[l - 1], 0);
      d[l - 1] += x;
      k += max(d[l - 1], 0);
    }
    if (r < n) {
      k -= max(d[r], 0);
      d[r] -= x;
      k += max(d[r], 0);
    }
    out.push((a0 + k + (a0 + k > 0)) / 2 | 0);
  }
  log(out.join('\n'))
}

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    let negSum = 0;
    let posSum = 0;
    if(n === 1){
        if(a[0] % 2 === 0)
            console.log(a[0]/2);
        else
            console.log(Math.ceil(a[0]/2));

        let q = pi(readline());
        while(q > 0){
            q--;
            let [l,r,x] = ti(readline().split(' '));
            a[0] += x;

            if(a[0] % 2 === 0){
                let res = a[0]/2;
                console.log(res === -0 ? 0 : res);
            }
            else{
                let res = Math.ceil(a[0]/2);
                console.log(res === -0 ? 0 : res);
            }
        }

        return;
    }

    for(let i = 1; i < n; i++){
        if(a[i] < a[i-1]){
            negSum += (a[i] - a[i-1]);
        }else{
            posSum += (a[i] - a[i-1]);
        }
    }

    let getMaxB = (maxC) => {
        let minB = a[0] - maxC;
        return posSum + minB;
    }

    console.log(Math.ceil((a[0] + posSum) / 2));
    let q = pi(readline());
    while(q > 0){
        q--;
        let [l, r, x] = ti(readline().split(' '));

        if(l-1 !== 0){
            let y = a[l-1] + x;
            if(a[l-2] > y){
                negSum += x;
            }else{
                posSum += x;
            }
        }

        if(r !== n){
            let y = a[r-1] + x;
            if(a[r-2] > y){
                negSum += x;
            }else{
                posSum += x;
            }
        }

        console.log(Math.ceil((a[0] + posSum) / 2));
    }
}

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

let inputString = '';
let currentLine = 0;

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

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    let negSum = 0;
    let posSum = 0;
    if(n === 1){
        if(a[0] % 2 === 0)
            console.log(a[0]/2);
        else
            console.log(Math.ceil(a[0]/2));

        let q = pi(readline());
        while(q > 0){
            q--;
            let [l,r,x] = ti(readline().split(' '));
            a[0] += x;

            if(a[0] % 2 === 0){
                let res = a[0]/2;
                console.log(res === -0 ? 0 : res);
            }
            else{
                let res = Math.ceil(a[0]/2);
                console.log(res === -0 ? 0 : res);
            }
        }

        return;
    }

    for(let i = 1; i < n; i++){
        if(a[i] < a[i-1]){
            negSum += (a[i] - a[i-1]);
        }else{
            posSum += (a[i] - a[i-1]);
        }
    }

    let getMaxB = (maxC) => {
        let minB = a[0] - maxC;
        return posSum + minB;
    }

    let findRes = () => {
        let st = -1000000000;
        let en = 1000000000;
        while(st <= en){
            let maxC = Math.floor((st+en)/2);
            let maxB = getMaxB(maxC);
            if(st === en){
                return st;
            }

            if(maxC === maxB){
                return maxC;
            }else if(maxC > maxB){
                en = maxC;
            }else{
                st = maxC+1;
            }
        }
    }

    console.log(findRes());
    let q = pi(readline());
    while(q > 0){
        q--;
        let [l, r, x] = ti(readline().split(' '));

        if(l-1 !== 0){
            let y = a[l-1] + x;
            if(a[l-2] > y){
                negSum += x;
            }else{
                posSum += x;
            }
        }

        if(r !== n){
            let y = a[r-1] + x;
            if(a[r-2] > y){
                negSum += x;
            }else{
                posSum += x;
            }
        }

        console.log(findRes());
    }
}

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    let negSum = 0;
    let posSum = 0;
    if(n === 1){
        if(a[0] % 2 === 0)
            console.log(a[0]/2);
        else
            console.log(Math.ceil(a[0]/2));

        let q = pi(readline());
        while(q > 0){
            q--;
            let [l,r,x] = ti(readline().split(' '));
            a[0] += x;

            if(a[0] % 2 === 0){
                let res = a[0]/2;
                console.log(res === -0 ? 0 : res);
            }
            else{
                let res = Math.ceil(a[0]/2);
                console.log(res === -0 ? 0 : res);
            }
        }

        return;
    }

    for(let i = 1; i < n; i++){
        if(a[i] < a[i-1]){
            negSum += (a[i] - a[i-1]);
        }else{
            posSum += (a[i] - a[i-1]);
        }
    }

    let getMaxB = (maxC) => {
        let minB = a[0] - maxC;
        return posSum + minB;
    }

    console.log(Math.ceil((a[0] + posSum) / 2));
    let q = pi(readline());
    while(q > 0){
        q--;
        let [l, r, x] = ti(readline().split(' '));

        if(l-1 !== 0){
            if(a[l-2] > a[l-1]){
                negSum -= (a[l-1]-a[l-2]);
            }else{
                posSum -= (a[l-1]-a[l-2]);
            }
            a[l-1] += x;
            if(a[l-2] > a[l-1]){
                negSum += (a[l-1]-a[l-2]);
            }else{
                posSum += (a[l-1]-a[l-2]);
            }
        }

        if(r < n){
            if(a[r-1] > a[r]){
                negSum -= (a[r]-a[r-1]);
            }else{
                posSum -= (a[r]-a[r-1]);
            }
            a[r-1] += x;
            if(a[r-1] > a[r]){
                negSum += (a[r]-a[r-1]);
            }else{
                posSum += (a[r]-a[r-1]);
            }
        }

        console.log(Math.ceil((a[0] + posSum) / 2));
    }
}


var x = readline().split(" ").map(x => Number(x));
var n = x[0];
var k = x[1];

var maxFlip = 2 * k + 1;

var ans = [];
if (n % maxFlip === 0) {
  for (var i = k + 1; i <= n; i += maxFlip) {
    ans.push(i);
  }
} else {
  var d = n % maxFlip;
  var f = Math.max(1, k + 1 - d / 2);
  for (var i = 1 + Math.floor(d / 2); i <= n; i += maxFlip) {
    ans.push(i);
  }
}
print(ans.length);
print(ans.join(' '));

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./sources/hackerrank/algorithms/practice/strings/highest-value-palindrome-copy/index.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./helpers/input-manager.js":
/*!**********************************!*\
  !*** ./helpers/input-manager.js ***!
  \**********************************/
/*! exports provided: InputManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputManager", function() { return InputManager; });
const fs = __webpack_require__(/*! fs */ "fs");

class InputManager {
    static getInput() {
        return new Promise((resolve) => {
            let input = '';

            if (fs.existsSync('./input.txt')) {
                input = fs.readFileSync('./input.txt').toString();
                resolve(this.parseInputString(input));
            } else {
                process.stdin.resume();
                process.stdin.setEncoding('utf-8');
                process.stdin.on('data', inputStdin => {
                    input += inputStdin;
                });

                process.stdin.on('end', () => {
                    resolve(this.parseInputString(input));
                });
            }
        });
    }

    static parseInputString(input) {
        return input.replace(/\s*$/, '')
            .split('\n')
            .map(str => str.replace(/\s*$/, ''));
    }
}

/***/ }),

/***/ "./helpers/solution-manager.js":
/*!*************************************!*\
  !*** ./helpers/solution-manager.js ***!
  \*************************************/
/*! exports provided: SolutionManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SolutionManager", function() { return SolutionManager; });
class SolutionManager {
    static printSolution(solutionFn) {
        let result = solutionFn();
        if (typeof result !== 'undefined') {
            if (Array.isArray(result)) {
                result.forEach(v => console.log(v));
            } else {
                console.log(result);
            }
        }
    }
}

/***/ }),

/***/ "./sources/hackerrank/algorithms/practice/strings/highest-value-palindrome-copy/index.js":
/*!***********************************************************************************************!*\
  !*** ./sources/hackerrank/algorithms/practice/strings/highest-value-palindrome-copy/index.js ***!
  \***********************************************************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _helpers_solution_manager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../../../../helpers/solution-manager */ "./helpers/solution-manager.js");
/* harmony import */ var _helpers_input_manager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../../../../helpers/input-manager */ "./helpers/input-manager.js");

_helpers_input_manager__WEBPACK_IMPORTED_MODULE_1__["InputManager"].getInput().then((input) => _helpers_solution_manager__WEBPACK_IMPORTED_MODULE_0__["SolutionManager"].printSolution(() => {
    let [n, k] = input.shift().split(' ').map(v => Number(v));
    let maxTurn = k * 2 + 1;
    let remainder = n % maxTurn;

    let i = remainder === 0 || remainder > maxTurn / 2 ? k : 0;
    let moves = [i];
    while (i + maxTurn <= n) {
        i += maxTurn;

        if (i === n && k === 0) {
            break;
        }

        moves.push(i);
    }

    console.log(moves.length);
    console.log(moves.map(v => v + 1).join(' '));
}));

/***/ }),

/***/ "fs":
/*!*********************!*\
  !*** external "fs" ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("fs");

/***/ })

/******/ });
//# sourceMappingURL=index.built.js.map

var x = readline().split(" ").map(x => Number(x));
var n = x[0];
var k = x[1];

var maxFlip = 2 * k + 1;

if (n <= maxFlip) {
  print(1);
  print(Math.min(n, k + 1));
} else {
  var d = n % maxFlip;
  var f = Math.max(1, Math.floor(k + 1 - d / 2));
  var ans = [];
  for (var i = f; i <= n; i += maxFlip) {
    ans.push(i);
  }
  print(ans.length);
  print(ans.join(' '));
}

var x = readline().split(" ").map(x => Number(x));
var n = x[0];
var k = x[1];

var maxFlip = 2 * k + 1;

if (n <= maxFlip) {
  print(1);
  print(Math.min(n, k + 1));
} else {
  var d = n % maxFlip;
  var f = Math.max(1, k + 1 - d / 2);
  var ans = [];
  for (var i = f; i <= n; i += maxFlip) {
    ans.push(i);
  }
  print(ans.length);
  print(ans.join(' '));
}

var x = readline().split(" ").map(x => Number(x));
var n = x[0];
var k = x[1];

var maxFlip = 2 * k + 1;

if (n <= maxFlip) {
  print(1);
  print(Math.min(n, k + 1));
} else {
  var d = n % maxFlip;
  var f = Math.max(1, k + 1 - d);
  var ans = [];
  for (var i = f; i < n; i += maxFlip) {
    ans.push(i);
  }
  print(ans.length);
  print(ans.join(' '));
}

var x = readline().split(" ").map(x => Number(x));
var n = x[0];
var k = x[1];

var maxFlip = 2 * k + 1;

if (n <= maxFlip) {
  print(1);
  print(Math.min(n, k + 1));
} else {
  var d = n % maxFlip;
  var f = Math.max(1, k + 1 - d);
  var ans = [];
  for (var i = f; i <= n; i += maxFlip) {
    ans.push(i);
  }
  print(ans.length);
  print(ans.join(' '));
}


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

var server = tmp[0];
var qlen = tmp[1];

var queue = [];
for(var i =0; i < server; i++)
{
    tmp = readline();
    queue.push(tmp.split(' ').map(Number));
}

var q = 0;
var qq = [];
var tm = queue[0][0];
var output = [];
for(var i = 0; i < server; i++)
{
    for(var j = 0; j < qq.length; j++)
    {
        if(qq[j] <= queue[i][0])
        {
            //var idx = qq.indexOf(qq[j]);
            qq.splice(j, 1);
            q--;
        } else {
            break;
        }
    }
    if(tm <= queue[i][0])
    {
        tm = queue[i][0] + queue[i][1];
        q = 0;
        write(tm);

    }else if(tm > queue[i][0] && q < qlen)
    {
        q++;
        qq.push(tm);
        tm += queue[i][1];
        write(tm);

    } else
    {
        write(-1);
    }
    write(' ');
}

var readInt = () => parseInt(readline())
var readIntArray = () => readline().split(' ').map(item => parseInt(item))
function range(a, b) {
    var res = []
    for (var i = a; i <= b; i++) {
        res.push(i)
    }
    return res
}
var inputData = readIntArray()
var n = inputData[0]
var b = inputData[1]
var res = []

var q = []
var h = 0

var s = 0
var f = 0
for (var i = 0; i < n; i++) {
    var inputData = readIntArray()
    var t = inputData[0]
    var d = inputData[1]

    s = t
    while (t > f) {
        if (q.length - h > 0) {
            qh = q[h++] //pop
            f += qh.v
            res[qh.i] = f
        }
        else break;
    }
    if (t >= f) {
        f = t
        if (q.length - h > 0) {
            qh = q[h++] //pop
            f += qh.v
             res[qh.i] = f

            if (q.length-h+1 <= b)
            {
                q.push({i:i, v:d})
            } else res[i] = -1

        }
        else {
            f += d
            res[i] = f
        }
    }
    else {
        if (q.length-h+1 <= b)
        {
            q.push({i:i, v:d})
        } else res[i] = -1
    }
}
while (q.length > h) {
        qh = q[h++] //pop
        f += qh.v
        res[qh.i] = f
}
print(res.join(' '))

var input = readline().split(' ')

var n = Number(input[0]),
    b = Number(input[1])

var endtime = 0,
    queue = []

var result = []

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

    var input = readline().split(' '),
        t = Number(input[0]),
        d = Number(input[1])

    var idx = findIndex(queue, t)

    if (t >= endtime) {
        endtime = t + d
        result.push(endtime)
    } else {
        if (queue.length - idx < b) {
            queue.push(endtime)
            endtime = endtime + d
            result.push(endtime)
        } else {
            result.push(-1)
        }
    }

}

function findIndex (array, value) {
    var from = 0, to = array.length
    while (to > from + 1) {
        var i = from + ((to - from) >>> 1)
        if (array[i] > value) {
            to = i
        } else {
            from = i
        }
    }

  return array[from] > value ? from : to
}

print(result.join(' ') + '\n')

var input = readline().split(' '), n = +input[0], b = +input[1], p = 0, q = [], result = [];

for (var i = 0; i < n; i++) {
	var query = readline().split(' ').map(Number);
	for (var j = 0; j < q.length; j++) {
		if (q[j] <= query[0]) {
			q.splice(j, 1);
		} else {
			break;
		}
	}
	if (p <= query[0]) {
		p = query[0] + query[1];
		q = [];
	} else if (q.length < (b + 1)) {
		p = p + query[1];
	} else {
		//print(-1);
		result.push(-1);
		continue;
	}
	query[2] = p;
	q.push(p);
	// print(p);
	result.push(p);
}

print(result.join(' '));

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
    input: process.stdin,
    // input: fs.createReadStream('src/day4/0.input1.json'),
    output: process.stdout,
    terminal: false,
});

let lines = [];

/**
 * Time complexity:
 * Space complexity:
 */
rl.on('line', function (line) {
    lines.push(line.trim().split(' ').map(Number));
}).on('close', () => {
    const length = lines[0][0];
    const maxQueue = lines[0][1];
    let freeMoment = 0;
    let momentQueue = [];

    const ableToPutInQueue = (t, queue) => {
        let l = 0,
            r = queue.length - 1;
        let pivot;

        if (l === r) {
            // l === r === 0
            return maxQueue >= 1;
        }

        if (r - l === 1) {
            if (t >= queue[l]) {
                return maxQueue >= 1;
            } else {
                return maxQueue >= 2;
            }
        }

        while (true) {
            pivot = Math.floor((l + r) / 2);
            if (queue[pivot] === t) {
                return queue.length - pivot - 1 <= maxQueue;
            }

            if (r - l === 1) {
                if (queue[l] > t) {
                    return queue.length - l <= maxQueue;
                }
                return queue.length - pivot - 1 <= maxQueue;
            }

            if (queue[pivot] >= t) {
                r = pivot;
            } else {
                l = pivot;
            }
        }
    };
    // const ableToPutInQueue = (t, queue) => {
    //     let count = 0;
    //     for (let i = queue.length - 1; i >= 0; i--) {
    //         if (queue[i] > t) {
    //             count++;
    //         }
    //         if (count > maxQueue) {
    //             return false;
    //         }
    //     }
    //     return true;
    // };

    for (let i = 1; i <= length; i++) {
        let t = lines[i][0];
        let d = lines[i][1];
        // is server free --> process
        // is server busy, and queue is not full --> push into the queue
        if (t > freeMoment) {
            freeMoment = t + d;
        } else if (ableToPutInQueue(t, momentQueue)) {
            freeMoment = freeMoment + d;
        } else {
            console.log(-1);
            continue;
        }
        console.log(freeMoment);
        momentQueue.push(freeMoment);
    }
});

var readline = require('readline');

var input = [];

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

// rl.prompt();

rl.on('line', function(cmd) {
  input.push(cmd);
});

// const string = `5 1
// 2 9
// 4 8
// 10 9
// 15 2
// 19 1`;

// input.push('6 1');
// input.push('2 9');
// input.push('4 8');
// input.push('10 9');
// input.push('15 2');
// input.push(' 19 1');
// input.push('10008348907 1');

rl.on('close', function(cmd) {
  let inputArray = input;
  // inputArray = input.split('\n');

  const infoQueries = inputArray[0]
    .split(' ')
    .filter(x => x)
    .map(s => parseInt(s, 10));

  inputArray.shift();

  const queries = inputArray
    .map(i =>
      i
        .split(' ')
        .filter(x => x)
        .map(s => parseInt(s, 10))
    )
    // .filter(q => q[0] <= 1000000000 && q[1] <= 1000000000)
    .map(q => ({
      startTime: q[0],
      processingTime: q[1],
      processedTime: 0
    }));

  const numberOfQueries = Math.min(infoQueries[0], queries.length);
  const queueSize = infoQueries[1];

  let timestamp = queries[0].startTime + queries[0].processingTime;
  queries[0].processedTime = timestamp;
  const queue = [];

  queue.push(timestamp);

  for (let i = 1; i < numberOfQueries; i++) {
    const query = queries[i];

    // Remove all processed queries
    while (queue.length && query.startTime >= queue[0]) {
      queue.shift();
    }

    if (query.startTime >= timestamp) {
      timestamp = query.startTime + query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
      continue;
    }

    if (queue.length > queueSize) {
      // console.log('exceeded!');
      query.processedTime = -1;
    } else {
      timestamp += query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
    }

    // console.log('queue', queue);
  }

  console.log(
    `${queries
      .map(x => x.processedTime)
      .filter(x => x)
      .join(' ')}`
  );

  process.exit(0);
});

var readline = require('readline');

var input = [];

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

// rl.prompt();

rl.on('line', function(cmd) {
  input.push(cmd);
});

// const string = `5 1
// 2 9
// 4 8
// 10 9
// 15 2
// 19 1`;

// input.push('6 1');
// input.push('2 9');
// input.push('4 8');
// input.push('10 9');
// input.push('15 2');
// input.push(' 19 1');
// input.push('10008348907 1');

rl.on('close', function(cmd) {
  let inputArray = input;
  // inputArray = input.split('\n');

  const infoQueries = inputArray[0]
    .split(' ')
    .filter(x => x)
    .map(s => parseInt(s, 10));

  inputArray.shift();

  const queries = inputArray
    .map(i =>
      i
        .split(' ')
        .filter(x => x)
        .map(s => parseInt(s, 10))
    )
    // .filter(q => q[0] <= 1000000000 && q[1] <= 1000000000)
    .map(q => ({
      startTime: q[0],
      processingTime: q[1],
      processedTime: 0
    }));

  const numberOfQueries = Math.min(infoQueries[0], queries.length);
  const queueSize = infoQueries[1];

  let timestamp = queries[0].startTime + queries[0].processingTime;
  queries[0].processedTime = timestamp;
  const queue = [];

  queue.push(timestamp);

  for (let i = 1; i < numberOfQueries; i++) {
    const query = queries[i];

    // Remove all processed queries
    while (queue.length && query.startTime >= queue[0]) {
      queue.shift();
    }

    if (query.startTime >= timestamp) {
      timestamp = query.startTime + query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
      continue;
    }

    if (queue.length > queueSize) {
      // console.log('exceeded!');
      query.processedTime = -1;
    } else {
      timestamp += query.processingTime;
      query.processedTime = timestamp;
      queue.push(timestamp);
    }

    // console.log('queue', queue);
  }

  s = queries
      .map(x => x.processedTime)
      .filter(x => x)
      .join(' ');
  console.log(s)

  process.exit(0);
});

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

var server = tmp[0];
var qlen = tmp[1];

var queue = [];
for(var i =0; i < server; i++)
{
    tmp = readline();
    queue.push(tmp.split(' ').map(Number));
}

var q = 0;
var qq = [];
var tm = queue[0][0];
var output = [];
for(var i = 0; i < server; i++)
{
    for(var j = 0; j < qq.length; j++)
    {
        if(qq[j] <= queue[i][0])
        {
            //var idx = qq.indexOf(qq[j]);
            qq.splice(j, 1);
            q--;
        } else {
            break;
        }
    }
    if(tm <= queue[i][0])
    {
        tm += queue[i][1];
        q = 0;
        write(tm);

    }else if(tm > queue[i][0] && q < qlen)
    {
        q++;
        qq.push(tm);
        tm += queue[i][1];
        write(tm);

    } else
    {
        write(-1);
    }
    write(' ');
}
//print(output.join(' '));

var input = readline().split(' ')
  , n = +input[0]
  , b = +input[1]
  , p = 0
  , q = []
  , result = [];

for (var i = 0; i < n; i++ ) {
    var query = readline().split(' ').map(Number);
	for (var j = 0; j < q.length; j++) {
		if (q[0][2] <= query[0]) {
			q.splice(j, 1);
		} else {
			break;
		}
	}
    if (p <= query[0]) {
        p = query[0] + query[1];
		q = [];
    } else if (q.length < (b + 1)) {
        p = p + query[1];
    } else {
        //print(-1);
        result.push(-1);
        continue;
    }
    query[2] = p;
    q.push(query);
    // print(p);
    result.push(p);
}

print(result.join(' '));

const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
    input: process.stdin,
    // input: fs.createReadStream('src/day4/0.input1.json'),
    output: process.stdout,
    terminal: false,
});

let lines = [];

/**
 * Time complexity:
 * Space complexity:
 */
rl.on('line', function (line) {
    lines.push(line.trim().split(' ').map(Number));
}).on('close', () => {
    const length = lines[0][0];
    const maxQueue = lines[0][1];
    let freeMoment = 0;
    let momentQueue = [];

    const ableToPutInQueue = (t, queue) => {
        let l = 0,
            r = queue.length - 1;
        let pivot;

        if (l === r) {
            // l === r === 0
            return maxQueue >= 1;
        }

        if (r - l === 1) {
            if (t >= queue[l]) {
                return maxQueue >= 1;
            } else {
                return maxQueue >= 2;
            }
        }

        while (true) {
            pivot = Math.floor((l + r) / 2);
            if (queue[pivot] === t || r - l === 1) {
                return queue.length - pivot - 1 <= maxQueue;
            }

            if (queue[pivot] >= t) {
                r = pivot;
            } else {
                l = pivot;
            }
        }
    };
    // const ableToPutInQueue = (t, queue) => {
    //     let count = 0;
    //     for (let i = queue.length - 1; i >= 0; i--) {
    //         if (queue[i] > t) {
    //             count++;
    //         }
    //         if (count > maxQueue) {
    //             return false;
    //         }
    //     }
    //     return true;
    // };

    for (let i = 1; i <= length; i++) {
        let t = lines[i][0];
        let d = lines[i][1];
        // is server free --> process
        // is server busy, and queue is not full --> push into the queue
        if (t > freeMoment) {
            freeMoment = t + d;
        } else if (ableToPutInQueue(t, momentQueue)) {
            freeMoment = freeMoment + d;
        } else {
            console.log(-1);
            continue;
        }
        console.log(freeMoment);
        momentQueue.push(freeMoment);
    }
});


// // Importing the module
// const readline = require("readline-sync");

// // Enter the number
// let s = String(readline.question());
// let array = [];
// let ab = 0;
// let ba = 0;

// if (s.length === 1) {
//     return;
// }

// else if (s.length === 2) {
//     if (s[0] === 'a' && s[1] === 'b') {
//         s = 'aa';
//     } else if (s[0] === 'b' && s[1] === 'a') {
//         s = 'aa';
//     }
// }

// for (let i = 0; i < s.length; ++i) {
//     if (s[i] === 'a' && s[i + 1] === 'b') {
//         ab++;
//     } else if (s[i] === 'b' && s[i + 1] === 'a') {
//         ba++
//     }
//     array.push(s[i]);
// }

// if (ab !== ba) {
//     let occurence = array.indexOf('a');

//     array[occurence] = 'b';
// }

process.stdin.setEncoding('utf-8');
const readline = require('readline'); // reading line

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data;

    } else if (count !== 0) {
        inputArr.push(data.trim());

        count--;
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        main()
        process.exit(0)
    }
})

function solve(str) {
    if (str[str.length - 1] === str[0]) {
        console.log(str)
    } else {
        const res = str.split('')
        res.splice(0, 1, str[str.length - 1])
        console.log(res.join(''))
    }
}

function main() {
    for (let i = 0; i < inputArr.length; i++) {
        solve(inputArr[i]);
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split('');
	    a[0] = a[a.length - 1];
	    var ans = '';
	    for(j = 0; j < a.length; j++){
	        ans += a[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--) {
		let s = rl();
		let n = s.length;

		let ans = s;
		if (s[0] != s[n - 1])
			ans = s[n - 1] + s.slice(1);

		console.log(ans);
	}
}

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

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

function main () {
	let t = rn();
	while (t--) {
		let s = rl();
		let n = s.length;

		let abcnt = bacnt = 0;
		for (let i = 0; i < n - 1; i++) {
			if (s[i] != s[i + 1]) {
				if (s[i] == 'a') abcnt++;
				else bacnt++;
			}
		}

		ans = s.split('');
		if (abcnt != bacnt)
			ans[n - 1] = s[n - 1] == 'a' ? 'b' : 'a';

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

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 str = lines[l++]
        output[i] = solve(str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(str) {
    let s1 = 0
    let s2 = 0
    for (let i = 1; i < str.length; i++) {
        const s = str[i - 1] + str[i]
        if (s === 'ab') s1++
        if (s === 'ba') s2++
    }
// console.log(s1, s2)
    if (s1 === s2) return str
    let d = Math.abs(s1 - s2)
    let a = 'a' // a -> b
    let b = 'b'
    if (s1 < s2) {
        a = 'b'
        b = 'a'
    }
    const ans = []
    for (let i = 0; i < str.length; i++) {
        if (d && str[i] === a && (!i || str[i - 1] !== b)) {
            ans.push(b)
            d--
        } else {
            ans.push(str[i])
        }
    }
    return ans.join('')
}

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        main()
        process.exit(0)
    }
})

function solve(str) {
    if (str[str.length - 1] === str[0]) {
        console.log(str)
    } else {
        const res = str.split('')
        res.splice(0, 1, str[str.length - 1])
        console.log(res.join(''))
    }
}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var s = nextCharArray();
		var N = s.length;
		if(s[0] != s[N - 1]){
			s[0] = s[N - 1];
		}
		myout(myconv(s, 0));
	}
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
	for(i = 1; i <= t; i++){
	    var a = lines[i].split('');
	    console.log(a);
	}
});


let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const map = {};
  const limit = Math.floor(len / 3);
  let [count124, count126, count136] = [0, 0, 0];
  for (let value of arr) {
    map[value] = (map[value] || 0) + 1;
  }

  if (
    map[1] >= limit &&
    ((map[1] && map[2] && map[4]) || (map[1] && map[2] && map[6]) || (map[1] && map[3] && map[6]))
  ) {
    if (map[1] > 0 && map[2] > 0 && map[4] > 0) {
      count124 = Math.min(map[1], map[2], map[4]);
      map[1] -= count124;
      map[2] -= count124;
      map[4] -= count124;
    }
    if (map[1] > 0 && map[2] > 0 && map[6] > 0) {
      count126 = Math.min(map[1], map[2], map[6]);
      map[1] -= count126;
      map[2] -= count126;
      map[6] -= count126;
    }
    if (map[1] > 0 && map[3] > 0 && map[6] > 0) {
      count136 = Math.min(map[1], map[3], map[6]);
      map[1] -= count136;
      map[3] -= count136;
      map[6] -= count136;
    }
    if (count124 + count126 + count136 === limit) {
      for (let i = 0; i < count124; i++) console.log(`${1} ${2} ${4}`);
      for (let i = 0; i < count126; i++) console.log(`${1} ${2} ${6}`);
      for (let i = 0; i < count136; i++) console.log(`${1} ${3} ${6}`);
    } else {
      console.log(-1);
    }
  } else {
    console.log(-1);
  }
}

var am = readline()
var nums = readline().split(' ')
var c1 = c2 = c3 = c4 = c6 = 0
for(var i=0; i<am; i++){
    switch(nums[i]){
        case 1:
            c1+=1;
    }
}
print(c1)

var num = readline()
var line = readline().split(' ')
print(num)


//constrains
//  * 1 <= t <= ^5
//  * -10^9 <= direction < 10^9

//Input
var firstLine = "5 0 0 1 1"; var direction = "SESNW";           // 4
// var firstLine = "10 5 3 3 6"; var direction = "NENSWESNEE";     // -1
// var firstLine = "19 172106364 468680119 172106365 468680119"; var direction = "SSEEESSSESESWSEESSS";
//              13
// var firstLine = "19 172106364 468680119 172106363 468680119"; var direction = "SSEEESSSESESWSEESSS";
// var firstLine = "1 0 0 0 -1"; var direction = "S";           // 4

var firstLine = readline(); var direction = readline();

retorno = eval(firstLine, direction);

//Solution
function eval(firstLine, direction){
    var tmp = firstLine.split(" ").map(function(x){ return parseInt(x)});
    var t = tmp[0];
    var start = {
        x: tmp[1],
        y: tmp[2]    };
    var end = {
        x: tmp[3],
        y: tmp[4]    };
    write( timeToReach(t, start, end, direction) );
    //console.log(timeToReach(t, start, end, direction));
};

function timeToReach(t, s, e, direction){
    var ap = {
        x: s.x,
        y: s.y};

    // console.log("s.x: " + s.x + "    s.y: " + s.y + "        e.x: " + e.x + "    e.y: " + e.y);
    // console.log("\nap.x: " + ap.x + "    ap.y: " + ap.y);
    // console.log("\nDx: " + Math.abs(e.x - s.x) + "    Dy: " + Math.abs(e.y - s.y) + "\n\n" );

    var totalCount = -1;
    for(var i = 0 ; i < t ; i++){
        //console.log(direction[i]);
        switch(direction[i]){
            case "N": // north direction
                if( Math.abs(e.y - (ap.y + 1)) < Math.abs(e.y - ap.y) ){
                    ap.y ++;
                };
                break;

            case "S": //south direction
                if( Math.abs(e.y - (ap.y - 1)) < Math.abs(e.y - ap.y) ){
                    ap.y --;
                };
                break;

            case "E": // east direction
                if( Math.abs(e.x - (ap.x + 1)) < Math.abs(e.x - ap.x) ){
                    ap.x++;
                };
                break;

            case "W": //west direction
            //console.log("entró");
                if( Math.abs(e.x - (ap.x - 1)) < Math.abs(e.x - ap.x) ){
                    //console.log("entró al if");
                    ap.x--;
                };
                break;
        };
        //console.log(i + "    ap.x: " + ap.x + "    ap.y: " + ap.y);
        // console.log("(e.x == ap.x) && (e.y == ap.y): " + ( (e.x == ap.x) && (e.y == ap.y) ) );
        if( (e.x == ap.x) && (e.y == ap.y) ){
            totalCount = i + 1;
            break;
        };
    };
    return totalCount;
};

function main()
{
    var tmp = readline().split(" ").map(function (x) { return parseInt(x); });
    var t = tmp[0],
        sx = tmp[1],
        sy = tmp[2],
        ex = tmp[3],
        ey = tmp[4];
    tmp = readline();
    var ans = 0;
    if ( sx > ex )
    {
        var i;
        var cnt = sx - ex;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "W" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    else if ( sx < ex )
    {
        var i;
        var cnt = ex - sx;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "E" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    if ( sy > ey )
    {
        var i;
        var cnt = sy - ey;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "S" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    else if ( sy < ey )
    {
        var i;
        var cnt = ey - sy;
        for ( i = 0; i < tmp.length && cnt > 0; i++ )
        {
            if ( tmp[i] == "N" )
            {
                cnt--;
            }
        }
        if ( cnt > 0 )
        {
            print(-1);
            return;
        }
        if ( ans < i )
            ans = i;
    }
    print(ans);
}

main();

function main(){
    var tmp = readline().split(" ").map(function (x) { return parseInt(x); });
    var t = tmp[0],
        sx = tmp[1],
        sy = tmp[2],
        ex = tmp[3],
        ey = tmp[4];
    tmp = readline();
    var ans = 0;
    if ( sx > ex ){
        var i;
        var cnt = sx - ex;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "W" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    else if ( sx < ex ){
        var i;
        var cnt = ex - sx;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "E" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    if ( sy > ey ){
        var i;
        var cnt = sy - ey;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "S" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    else if ( sy < ey ){
        var i;
        var cnt = ey - sy;
        for ( i = 0; i < tmp.length && cnt > 0; i++ ){
            if ( tmp[i] == "N" ){
                cnt--;
            }
        }
        if ( cnt > 0 ){
            print(-1);
            return;
        }
        if ( ans < i ){
            ans = i;
        }
    }
    print(ans);
}

main();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}

function main() {
  const [len, sx, sy, ex, ey] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const str = readLine();
  const [diffX, diffY] = [ex - sx, ey - sy];
  let [x, countX, y, countY] = ["", Math.abs(diffX), "", Math.abs(diffY)];

  if (diffX > 0) x = "E";
  else x = "W";
  if (diffY > 0) y = "N";
  else y = "S";

  let map = {};
  for (let i = 0; i < len; i++) {
    const char = str[i];

    map[char] = (map[char] || 0) + 1;

    if (diffX === 0 && map[y] >= countY) {
      console.log(i + 1);
      return;
    } else if (diffY === 0 && map[x] >= countX) {
      console.log(i + 1);
      return;
    } else if (map[x] >= countX && map[y] >= countY) {
      console.log(i + 1);
      return;
    }
  }

  console.log(-1);
}


let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const items = readLine()
    .split(" ")
    .reduce((obj, n, index) => {
      obj[n] = index;
      return obj;
    }, {});
  const queryLen = +readLine();
  const queries = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [person1, person2] = [0, 0];

  for (query of queries) {
    const position = items[query] + 1;
    if (position > 0) {
      person1 += position;
      person2 += len - position + 1;
    }
  }
  console.log(`${person1} ${person2}`);
}

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]] !== 0) {
            totalBeginChecks += ((i + 1) * queryFlag[list[i]]);
            totalEndChecks += ((list.length - i) * queryFlag[list[i]]);
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(1000000).fill(0);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] += 1;
    }
    console.log(solve().join(' '));
});

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]] !== 0) {
            totalBeginChecks += ((i + 1) * queryFlag[list[i]]);
            totalEndChecks += ((list.length - i) * queryFlag[list[i]]);
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(100001).fill(0);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] += 1;
    }
    console.log(solve().join(' '));
});

//Effective Approach

const {EOL} = require('os');

let inp = '';

process.stdin.on('data', c => inp += c);

process.stdin.on('end', () => {
    let lines = inp.split(EOL);

    let dex = {};
    for(let i = 1; i <= 100000; i++)  {
    	dex[i] = -1;
    }

    let n = lines[1].split(' ').map(c => +c);

    for(let i = 0; i < n.length; i++)  {
    	dex[n[i]] = i;
    }

    let c = lines[3].split(' ').map(r => +r);

    let tota = 0, totb = 0;
    for(let i = 0; i < c.length; i++)  {
    	if(dex[c[i]] != -1)  {
    		tota += dex[c[i]] + 1;
    		totb += n.length - dex[c[i]];
    	}
    }

    process.stdout.write(tota + ' ' + totb);

    return;
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function multiply(a, b) {
	a = a.toString(10).split('').reverse();
	b = b.toString(10).split('').reverse();

	if (a.length < b.length) {
		[a, b] = [b, a];
	}

	let res = Array(a.length + b.length).fill(0);
	for (let i = 0, lb = b.length; i < lb; ++i) {
		let carry = 0;
		let scarry = 0;
		for (let j = 0, la = a.length; j < la; ++j) {
			let m = b[i] * a[j];
			m += carry;

			if (m > 9) {
				let [c, d] = m.toString(10).split('');
				res[i + j] += (scarry >> 0) + (d >> 0);
				carry = c >> 0;
			} else {
				res[i + j] += (scarry >> 0) + m;
				carry = 0;
			}

			if (res[i + j] > 9) {
				let [c, d] = res[i + j].toString(10).split('');
				res[i + j] = d >> 0;
				scarry = c;
			} else {
				scarry = 0;
			}
		}
		if (carry > 0) res[a.length + i] = carry;
		if (scarry > 0) res[a.length + i] = scarry;
	}

	res.reverse();
	let mulVal = '';
	let flag = false;
	res.forEach(d => {
		if (!flag && d !== 0) flag = true;
		if (flag) mulVal += d;
	});
	return mulVal;
}

function main() {
	let n = readLine() >> 0;
	let nums = readLine()
		.split(' ')
		.map(x => x >> 0);
	let m = readLine() >> 0;
	let b = readLine()
		.split(' ')
		.map(x => x >> 0);

	let query = {};
	b.forEach(x => (query[x] = (query[x] || 0) + 1));

	let i = 0;
	let l = 0,
		r = 0;
	while (i < n) {
		if (query[nums[i]] !== undefined && query[nums[i]] > 0) {
			l += (i + 1) * query[nums[i]];
			r += (n - i) * query[nums[i]];
		}
		i++;
	}
	console.log(l, r);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
// function main() {
//     let n = parseInt(readLine());
//     let mainArray = readLine().split(' ').map(Number);
//     let m = parseInt(readLine());
//     let qureyArray = readLine().split(' ').map(Number);
//     let Vasyacount = 0;
//     for (let i = 0; i < qureyArray.length; i++) {
//         for (let j = 0; j < mainArray.length; j++) {
//             Vasyacount++;
//             if (qureyArray[i] === mainArray[j]) {
//                 break;
//             }
//         }
//     }

//     let Petyas_count = 0;
//     for (let i = 0; i < qureyArray.length; i++) {
//         for (let j = mainArray.length - 1; j >= 0; j--) {
//             Petyas_count++;
//             if (qureyArray[i] === mainArray[j]) {
//                 break;
//             }
//         }
//     }

//     console.log(Vasyacount, Petyas_count);
// }

function main() {
    let n = parseInt(readLine());
    let mainArray = readLine().split(' ').map(Number);
    let m = parseInt(readLine());
    let qureyArray = readLine().split(' ').map(Number);

    let indexArray = new Array(n);
    for (let i = 0; i < n; i++) {
        let test = mainArray[i];
        indexArray[test] = i;
    }
    let Vasya = 0;
    // console.log(indexArray);
    // console.log(indexArray[qureyArray[2]] + 1);

    for (let i = 0; i < m; i++) {
        Vasya = Vasya + indexArray[qureyArray[i]] + 1;
    }
    let Petya = 0;
    for (let i = 0; i < m; i++) {
        Petya = Petya + (n - indexArray[qureyArray[i]]);
    }
    console.log(Vasya, Petya);
}

var arrayLength = readline();
var input = {};
readline().split(" ").map((entry, index) => input[entry] = index);

var searchLength = readline();
var searchFor = readline().split(" ");

counterA = 0;
counterB = 0;
var index;
for (var j = 0; j < searchLength; j++) {
    index = input[searchFor[j]];
   counterA += index + 1;
   counterB += arrayLength - index;

}
print(counterA + " " + counterB);

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]]) {
            totalBeginChecks += i + 1;
            totalEndChecks += list.length - i;
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(100000).fill(false);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] = true;
    }
    console.log(solve().join(' '));
});

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

function search(element) {
    let begin = 0;
    let end = 0;
    let isBeginFound = false;
    let isEndFound = false;
    for (let i = 0; i < list.length; i++) {
        if (isBeginFound && isEndFound)
            break;
        if (list[i] !== element && !isBeginFound) {
            begin++;
        } else if (list[i] === element && !isBeginFound) {
            begin++;
            isBeginFound = true;
        }
        if (list[list.length - i - 1] !== element && !isEndFound) {
            end++;
        } else if (list[list.length - i - 1] === element && !isEndFound) {
            end++;
            isEndFound = true;
        }
    }
    return {begin, end};
}

let listLength;
let list;
let queryLength;
let query;
let queryFlag;

function solve() {
    let totalBeginChecks = 0;
    let totalEndChecks = 0;
    for (let i = 0; i < list.length; i++) {
        if (queryFlag[list[i]] !== 0) {
            totalBeginChecks += ((i + 1) * queryFlag[list[i]]);
            totalEndChecks += ((list.length - i) * queryFlag[list[i]]);
        }
    }
    return [totalBeginChecks, totalEndChecks]

}

rl.on('line', (line) => {
    if (!listLength) {
        listLength = parseInt(line);
        return;
    }
    if (!list) {
        list = line.split(' ').map(Number);
        return;
    }
    if (!queryLength) {
        queryLength = parseInt(line);
        return;
    }
    if (!query) {
        query = line.split(' ').map(Number);
    }
    queryFlag = new Array(100000).fill(0);
    for (let i = 0; i < query.length; i++) {
        queryFlag[query[i]] += 1;
    }
    console.log(solve().join(' '));
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function multiply(a, b) {
	a = a.toString(10).split('').reverse();
	b = b.toString(10).split('').reverse();

	if (a.length < b.length) {
		[a, b] = [b, a];
	}

	let res = Array(a.length + b.length).fill(0);
	for (let i = 0, lb = b.length; i < lb; ++i) {
		let carry = 0;
		let scarry = 0;
		for (let j = 0, la = a.length; j < la; ++j) {
			let m = b[i] * a[j];
			m += carry;

			if (m > 9) {
				let [c, d] = m.toString(10).split('');
				res[i + j] += (scarry >> 0) + (d >> 0);
				carry = c >> 0;
			} else {
				res[i + j] += (scarry >> 0) + m;
				carry = 0;
			}

			if (res[i + j] > 9) {
				let [c, d] = res[i + j].toString(10).split('');
				res[i + j] = d >> 0;
				scarry = c;
			} else {
				scarry = 0;
			}
		}
		if (carry > 0) res[a.length + i] = carry;
		if (scarry > 0) res[a.length + i] = scarry;
	}

	res.reverse();
	let mulVal = '';
	let flag = false;
	res.forEach(d => {
		if (!flag && d !== 0) flag = true;
		if (flag) mulVal += d;
	});
	return mulVal;
}

function main() {
	let n = readLine() >> 0;
	let nums = readLine()
		.split(' ')
		.map(x => x >> 0);
	let m = readLine() >> 0;
	let b = readLine()
		.split(' ')
		.map(x => x >> 0);

	let query = {};
	b.forEach(x => (query[x] = (query[x] || 0) + 1));

	let i = 0;
	let l = 0,
		r = 0;
	while (i < n) {
		if (query[nums[i]] !== undefined && query[nums[i]] > 0) {
			l += i + 1;
			r += n - i;
		}
		i++;
	}
	console.log(l, r);
}