Recently, Polycarp completed $$$n$$$ successive tasks.For each completed task, the time $$$s_i$$$ is known when it was given, no two tasks were given at the same time. Also given is the time $$$f_i$$$ when the task was completed. For each task, there is an unknown value $$$d_i$$$ ($$$d_i>0$$$) — duration of task execution.It is known that the tasks were completed in the order in which they came. Polycarp performed the tasks as follows:  As soon as the very first task came, Polycarp immediately began to carry it out.  If a new task arrived before Polycarp finished the previous one, he put the new task at the end of the queue.  When Polycarp finished executing the next task and the queue was not empty, he immediately took a new task from the head of the queue (if the queue is empty — he just waited for the next task). Find $$$d_i$$$ (duration) of each task.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The descriptions of the input data sets follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains exactly $$$n$$$ integers $$$s_1 < s_2 < \dots < s_n$$$ ($$$0 \le s_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ integers $$$f_1 < f_2 < \dots < f_n$$$ ($$$s_i < f_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print $$$n$$$ positive integers $$$d_1, d_2, \dots, d_n$$$ — the duration of each task.

NoteFirst test case:The queue is empty at the beginning: $$$[ ]$$$. And that's where the first task comes in. At time $$$2$$$, Polycarp finishes doing the first task, so the duration of the first task is $$$2$$$. The queue is empty so Polycarp is just waiting.At time $$$3$$$, the second task arrives. And at time $$$7$$$, the third task arrives, and now the queue looks like this: $$$[7]$$$.At the time $$$10$$$, Polycarp finishes doing the second task, as a result, the duration of the second task is $$$7$$$.And at time $$$10$$$, Polycarp immediately starts doing the third task and finishes at time $$$11$$$. As a result, the duration of the third task is $$$1$$$.    An example of the first test case.

T = readline()
while (T--) {
   n = readline()
   s = readline().split(' ').map(a => +a)
   f = readline().split(' ').map(b => +b)
   a = []
   a[0] = f[0] - s[0]
   for(i=1; i<n; i++){
      if(s[i]>f[i-1]){
         a.push(f[i] - s[i])
      }
      else{
         a.push(f[i] - f[i-1])
      }
   }

   print( a.join(' '))
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var taskStartArray = readline().split(" ");
    var taskEndArray = readline().split(" ");
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            var taskStart = parseInt(taskStartArray[j]);
            var prevTaskEnd = parseInt(taskEndArray[j-1]);
            var startTime = Math.max(taskStart, prevTaskEnd);
            var taskTime = parseInt(taskEndArray[j]) - startTime;
            result += `${taskTime} `;
        }
        else
        {
            var taskTime = parseInt(taskEndArray[j]) - parseInt(taskStartArray[j]);
            result += `${taskTime} `;
        }
    }
    print(result);
}

var tests = parseInt(readline());
    var n, s, f;
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        s = readline().split(' ').map(x => parseInt(x));
        f = readline().split(' ').map(x => parseInt(x));
        var d = [f[0] - s[0]];
        for (var i = 1; i < n; i++) {
            var start = Math.max(s[i], f[i-1]);
            var diff = f[i] - start;
            d.push(diff);
        }
        print(d.join(' '));
    }

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            const l=_data.split('\n');
            this.data = this.data.concat(l.slice(0,-1).map(string=>string.trim()),l[l.length-1] );
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        let ans="";
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
             ans+=Math.max(0, d) + " ";
            stopAt =f[i];
        }
        print(ans+"\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

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

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

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

solve = () => {
    const t = parseInt(readline());
    for (let j = 0; j < t; j++) {
        const n = parseInt(readline());
        const s = readline().split(" ").map(Number);
        const f = readline().split(" ").map(Number);
        var d = [];
        for (let i = 1; i < n + 1; i++) {
            d[0] = f[0] - s[0];
            if (s[i] < f[i] && s[i] >= f[i - 1]) {
                d.push(f[i] - s[i]);
            }
            if (s[i] < f[i - 1]) {
                d.push(f[i] - f[i - 1]);
            }
        }
        console.log(d.join(" "));

    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let S = readline().split(' ').map(Number);
        let F = readline().split(' ').map(Number);
        let D = [];

        let t = 0;
        for (let i = 0; i < n; i++) {
            t = Math.max(S[i], t);
            D[i] = F[i] - t;
            t = F[i];
        }

        output(D.join(' '));
    }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
  let t = parseInt(readline());
  while (t--) {
       let n = parseInt(readline());
       let arr1 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr2 = readline().trim().split(" ").map(cur=>parseInt(cur));
       let res = [];
       res.push(arr2[0]-arr1[0]);
       for(let i=1;i<n;i++){
            if(arr2[i-1]<arr1[i]) res.push(arr2[i]-arr1[i]);
            else res.push(arr2[i]-arr2[i-1]);
       }
       console.log(res.join(" "));
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

function main() {
    const testCaseCount = Number(readline())

    for (let index = 0; index < testCaseCount; index++) {

        const taskCount = Number(readline());
        const taskStartTimes = readline().split(" ").map(n => Number(n));
        const taskEndTimes = readline().split(" ").map(n => Number(n));

        const durations = [];

        for (let taskTimeIndex = 0; taskTimeIndex < taskCount; taskTimeIndex++) {
            const endTime = taskEndTimes[taskTimeIndex];

            const startProcessingTime = taskTimeIndex === 0 ?
                taskStartTimes[taskTimeIndex] :
                Math.max(taskStartTimes[taskTimeIndex], taskEndTimes[taskTimeIndex - 1]);

                durations.push(endTime - startProcessingTime);
        }

        print(durations.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 n = +lines[l++]
        const sa = lines[l++].trim().split(' ').map(Number)
        const sb = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, sa, sb)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, sa, sb) {
    const cs = []
    sa.forEach(x => {
        cs.push([x, 1])
    })
    sb.forEach(x => {
        cs.push([x, -1])
    })
    const ans = []
    const sorted = cs.sort((a, b) => a[0] - b[0])
    // console.log(sorted)
    let prev
    let now = 0
    sorted.forEach(([x, d]) => {
        if (d < 0) {
            ans.push(x - prev)
        }
        //
        now += d
        if (now === 1) {
            // the first
            prev = x
        } else if (d < 0) {
            prev = x
        }
    })
    return ans.join(' ')
}

'use strict';

function solve(n, a, b) {
  const times = new Array(n);
  for (let i = 0; i < n; i++) {
    times[i] = [a[i], b[i]];
  }
  times.sort((a, b) => a[0] - b[0]);
  const res = new Array(n);
  let t = -1;
  for (let [i, [x, y]] of times.entries()) {
    if (t === -1) {
      res[i] = y - x;
    } else {
      res[i] = y - Math.max(x, t);
    }
    t = y;
  }
  return res.join(' ');
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      const b = (await read()).split(' ').map(Number);
      res.push(solve(n, a, b));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

T = readline()
while (T--) {
   n = readline()
   s = readline().split(' ').map(a => +a)
   f = readline().split(' ').map(b => +b)
   a = []
   a[0] = f[0]
   for(i=1; i<n; i++){
      if(s[i]>a[i-1]){
         a.push(f[i] - s[i])
      }
      else{
         a.push(f[i] - f[i-1])
      }
   }

   print( a.join(' '))
}

T = readline()
while (T--) {
   n = readline()
   s = readline().split(' ').map(a => +a)
   f = readline().split(' ').map(b => +b)
   a = []
   a[0] = f[0]
   for(i=1; i<n; i++){
      if(s[i]>a[i-1]){
         a.push(f[i] - s[i])
      }
      else{
         a.push(f[i] - f[i-1])
      }
   }
   print(a)
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var taskStartArray = readline().split(" ");
    var taskEndArray = readline().split(" ");
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (j !== 0)
        {
            var taskStart = parseInt(taskStartArray[j]);
            var prevTaskEnd = parseInt(taskEndArray[j-1]);
            var startTime = Math.max(taskStart, prevTaskEnd);
            var taskTime = parseInt(taskEndArray[j]) - startTime;
            result += `${taskTime}`;
        }
        else
        {
            var taskTime = parseInt(taskEndArray[j]) - parseInt(taskStartArray[j]);
            result += `${taskTime}`;
        }
    }
    print(result);
}

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        let ans="";
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d)){
                print("("+s+"|"+f+")")
                ans="";
            }
            else
             ans+=Math.max(0, d) + " ";
            stopAt =f[i];
        }
        print(ans+"\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b("+s+"|"+f+")")
            else
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s+"|"+f+")")
            else
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s+"|"+f+")")
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s.length+","+f.length+")")
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            if (isNaN(d))
                print("("+s[i]+","+f[i]+")")
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length <2 ) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//-----------------------the-code---------------------------------
//----------------------------------------------------------------
(async () => {
    /* x=await read();
    print("|"+x+"|"); */
    let t = parseInt(await read());
    while (t--) {
        _ = await read();
        let s = await read();
        let f = await read();
        s = s.split(' ').map(Number);
        f = f.split(" ").map(Number);
        let stopAt = 0;
        for (var i = 0; i < s.length; i++) {
            let d = f[i] - Math.max(s[i], stopAt);
            print(Math.max(0, d) + " ");
            stopAt =f[i];
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner {
    data = [];
    constructor() {
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data', _data => {
            let lasttext=this.data.pop();
            if(lasttext== undefined)
                lasttext=""
            _data =lasttext+_data;
            this.data = this.data.concat(_data.split('\n').map(string=>string.trim()));
        });
    }
    read = async () => {
        process.stdin.resume();
        while (this.data.length == 0) {
            await delay(0);
        }
        process.stdin.pause();
        let res=this.data.shift();
        if(res=="")
             return await read();
        return res;
    };
}
delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const print = (text) => process.stdout.write("" + text);
const scaner = new Scaner()
const read = async () => await scaner.read();
//----------------------------------------------------------------
//----------------------------------------------------------------
//----------------------------------------------------------------
(async ()=>{
    // x=await read();
    // print(x);
    let t = parseInt(await read());
    while(t--){
        _ = await read();
        let s = await read();
        let f = await read();
        s=s.split(" ");
        f=f.split(" ");
        let stopAt=0;
        for(var i =0;i< s.length ;i++)
        {
            let d=parseInt(f[i])-Math.max(parseInt(s[i]),stopAt);
            print(Math.max(0,d)+ " ");
            stopAt=d==0?stopAt:parseInt(f[i]);
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

class Scaner{
    data=[];
    constructor(){
        process.stdin.setEncoding('utf-8');
        process.stdin.on('data',_data=>
        {
            this.data =this.data.concat(_data.trim().split('\n').map(string => {
                return string.trim();
            }));
        });
    }
    read=async()=>
    {
        process.stdin.resume();
        while(this.data.length == 0)
        {
            await delay(0);
        }
        process.stdin.pause();
        return this.data.shift();
    };
}

delay = (ms)=> new Promise(
    resolve => setTimeout(resolve, ms));
const print=(text)=>process.stdout.write(""+text);
const scanl= ()=> new Promise(
    resolve=>
    {
        process.stdin.resume();
        process.stdin.once('data',data=>
        {
            process.stdin.pause();
            resolve(data.trim().substring(0,data.length-2))
        })
    });
const scaner=new Scaner()
const read= async ()=>  await scaner.read();
//----------------------------------------------------------------
(async ()=>{
    // x=await read();
    // print(x);
    let t = parseInt(await read());
    while(t--){
        _ = await read();
        let s = await read();
        let f = await read();
        s=s.split(" ");
        f=f.split(" ");
        let stopAt=0;
        for(var i =0;i< s.length ;i++)
        {
            let d=parseInt(f[i])-Math.max(parseInt(s[i]),stopAt);
            print(Math.max(0,d)+ " ");
            stopAt=d==0?stopAt:parseInt(f[i]);
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

delay = (ms)=> new Promise(
    resolve => setTimeout(resolve, ms));
const print=(text)=>process.stdout.write(""+text);
const scanl= ()=> new Promise(
    resolve=>process.stdin.once('data',data=>
        {
            resolve(data.toString().substring(0,data.length-2))
        }));
//----------------------------------------------------------------
(async ()=>{
    let t = parseInt(await scanl());
    while(t--){
        _ = await scanl();
        let s = await scanl();
        let f = await scanl();
        s=s.split(" ");
        f=f.split(" ");
        let stopAt=0;
        for(var i =0;i< s.length ;i++)
        {
            let d=parseInt(f[i])-Math.max(parseInt(s[i]),stopAt);
            print(Math.max(0,d)+ " ");
            stopAt=d==0?stopAt:parseInt(f[i]);
        }
        print("\n");
    }
})().then(() => {
}).catch(() => {
    console.log("error");
});

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

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

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

solve = () => {
    const t = parseInt(readline());

    for (let j = 0; j < t; j++) {
        const n = parseInt(readline());
        const s = readline().split(" ").map(Number);
        const f = readline().split(" ").map(Number);
        var d = [];
        for (let i = 1; i < n + 1; i++) {
            d[0] = f[0] - s[0];
            if (s[i] < f[i] && s[i] > f[i - 1]) {
                d.push(f[i] - s[i]);
            }
            if (s[i] < f[i - 1]) {
                d.push(f[i] - f[i - 1]);
            }
        }
        console.log(d.join(" "));
    }
}

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

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

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

solve = () => {
    const t = parseInt(readline());

    for (let j = 0; j < t; j++) {
        const n = parseInt(readline());
        const s = readline().split(" ").map(Number);
        const f = readline().split(" ").map(Number);
        var d = [];

        for (let i = 1; i < n + 1; i++) {
            d[0] = f[0] - s[0];
            if (s[i] < f[i] && s[i] > f[i - 1]) {
                d.push(f[i] - s[i]);
            }
            if (s[i] < f[i - 1]) {
                d.push(f[i] - f[i - 1]);
            }
        }
        console.log(d);
    }
}


Vasya came up with a password to register for EatForces — a string $$$s$$$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords "abaCABA12", "Z7q" and "3R24m" are valid, and the passwords "qwerty", "qwerty12345" and "Password" are not. A substring of string $$$s$$$ is a string $$$x = s_l s_{l + 1} \dots s_{l + len - 1} (1 \le l \le |s|, 0 \le len \le |s| - l + 1)$$$. $$$len$$$ is the length of the substring. Note that the empty string is also considered a substring of $$$s$$$, it has the length $$$0$$$.Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of $$$s$$$ should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of testcases. Each of the next $$$T$$$ lines contains the initial password $$$s~(3 \le |s| \le 100)$$$, consisting of lowercase and uppercase Latin letters and digits. Only $$$T = 1$$$ is allowed for hacks.

For each testcase print a renewed password, which corresponds to given conditions.  The length of the replaced substring is calculated as following: write down all the changed positions. If there are none, then the length is $$$0$$$. Otherwise the length is the difference between the first and the last changed position plus one. For example, the length of the changed substring between the passwords "abcdef" $$$\rightarrow$$$ "a7cdEf" is $$$4$$$, because the changed positions are $$$2$$$ and $$$5$$$, thus $$$(5 - 2) + 1 = 4$$$. It is guaranteed that such a password always exists. If there are several suitable passwords — output any of them.

NoteIn the first example Vasya's password lacks a digit, he replaces substring "C" with "4" and gets password "abcD4E". That means, he changed the substring of length 1.In the second example Vasya's password is ok from the beginning, and nothing has to be changed. That is the same as replacing the empty substring with another empty substring (length 0).

var t = +readline();
while (t-->0){
    var pass = readline(),lower = 0,upper = 0,digit=0;
    var check = new Array(pass.length);
    pass = pass.split('');
    pass.forEach((x,i)=>{
        x = x.charCodeAt();
        if (x >= 65 && x <= 90) {
            upper++;
            check[i] = 'u';
        }
        else if (x >= 97 && x <= 122){
          lower++;
          check[i] = 'l';
        }
        else {
            digit++;
            check[i] = 'd';
        }
    });
    if (lower!== 0 && upper!==0 && digit===0){
        for (var i = 1;i<pass.length;i++){
            if ((check[i] === 'l' && lower >= upper) || (check[i] === 'u' && upper >= lower)){
                pass[i] = '0';
                break;
            }
        }
    } else if (lower!== 0 && upper===0 && digit!==0){
        for (var i = 1;i<pass.length;i++){
            if ((check[i] === 'l' && lower >= digit) || (check[i] === 'd' && digit >= lower)){
                pass[i] = 'A';
                break;
            }
        }
    } else if (lower=== 0 && upper!==0 && digit!==0){
        for (var i = 1;i<pass.length;i++){
            if ((check[i] === 'u' && upper >= digit) || (check[i] === 'd' && digit >= upper)){
                pass[i] = 'a';
                break;
            }
        }
    } else if (upper!== 0 && digit === 0 && lower === 0) {
        pass[0] = '0';
        pass[1] = 'a';
    } else if (upper=== 0 && digit === 0 && lower !== 0){
        pass[0] = '0';
        pass[1] = 'A';
    } else if (upper=== 0 && digit !== 0 && lower === 0) {
        pass[0] = 'A';
        pass[1] = 'a';
    }
    var res = '';
    pass.forEach(x=>res+=x);
    print(res);
}

const readline = require('readline');
const fs = require('fs')
const rl = readline.createInterface({
   input: process.stdin,
//   input : fs.createReadStream('practice/codeforces/test.in'),
  output: process.stdout
});
num = 0
rl.on('line', str => {
  if (num == 0) {
    num = str
  } else {
    func(str)
  }
});
isdigit = a => a <= 9 && a >= 0
isLower = a => a <= 'z' && a >= 'a'
isUpper = a => a <= 'Z' && a >= 'A'
function func(str) {
  n = 0;
  l = 0;
  u = 0;
  for (char of str) {
    if (isdigit(char)) {
      n += 1
    } else if (isLower(char)) {
      l += 1
    } else if (isUpper(char)) {
      u += 1
    }
  }
  if (n && l && u) {
    console.log(str)
    return;
  }
  if (n == 0 && l == 0) {
    console.log('1a' + str.slice(2))
  } else if (n == 0 && u == 0) {
    console.log('1A' + str.slice(2))
  } else if (l == 0 && u == 0) {
    console.log('aA' + str.slice(2))
  }
  else {
    if (n == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isUpper(str[0]) && isUpper(str[1])) ) {
        console.log('1' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + '1' + str.slice(3))
      }
    }else if (l == 0) {
      if ((isdigit(str[0]) && isdigit(str[1])) ||
        (isUpper(str[0]) && isUpper(str[1]))
      ) {
        console.log('a' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'a' + str.slice(3))
      }
    } else if (u == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isdigit(str[0]) && isdigit(str[1]))
      ) {
        console.log('A' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'A' + str.slice(3))
      }
    }
  }
}

var t = +readline();
while (t-->0){
    var pass = readline(),lower = false,upper = false,digit=false;
    var check = new Array(pass.length);
    pass.split('').forEach((x,i)=>{
        x = x.charCodeAt();
        if (x >= 65 && x <= 90) {
            upper = true;
            check[i] = 'u';
        }
        else if (x >= 97 && x <= 122){
          lower = true;
          check[i] = 'l';
        }
        else {
            digit = true;
            check[i] = 'd';
        }
    });
    pass = pass.split('');
    if (lower && upper && !digit){
        for (var i = 1;i<pass.length;i++){
            if (check[i] === check[i-1]){
                pass[i] = '0';
                break;
            }
        }
    } else if (lower && digit && !upper){
        for (var i = 1;i<pass.length;i++){
            if (check[i] === check[i-1]){
                pass[i] = 'A';
                break;
            }
        }
    } else if (upper && digit && !lower){
        for (var i = 1;i<pass.length;i++){
            if (check[i] === check[i-1]){
                pass[i] = 'a';
                break;
            }
        }
    } else if (upper && !digit && !lower) {
        pass[0] = '0';
        pass[1] = 'a';
    } else if (lower && !digit && !upper){
        pass[0] = '0';
        pass[1] = 'A';
    } else if (digit && !lower && !upper) {
        pass[0] = 'A';
        pass[1] = 'a';
    }
    var res = '';
    pass.forEach(x=>res+=x);
    print(res);
}

const readline = require('readline');
const fs = require('fs')
const rl = readline.createInterface({
  input: process.stdin,
  // input : fs.createReadStream('practice/codeforces/test.in'),
  output: process.stdout
});
num = 0
rl.on('line', str => {
  if (num == 0) {
    num = str
  } else {
    func(str)
  }
});
isdigit = a => a <= 9 && a >= 0
isLower = a => a <= 'z' && a >= 'a'
isUpper = a => a <= 'Z' && a >= 'A'
function func(str) {
  n = 0;
  l = 0;
  u = 0;
  for (char of str) {
    if (isdigit(char)) {
      n += 1
    } else if (isLower(char)) {
      l += 1
    } else if (isUpper(char)) {
      u += 1
    }
  }
  if (n && l && u) {
    console.log(str)
    return;
  }
  if (n == 0 && l == 0) {
    console.log('1a' + str.slice(2))
  } else if (n == 0 && u == 0) {
    console.log('1A' + str.slice(2))
  } else if (l == 0 && u == 0) {
    console.log('aA' + str.slice(2))
  }
  else {
    if (n == 0) {
      if (isLower(str[0]) && isLower(str[1])) {
        console.log('1' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + '1' + str.slice(3))
      }
    }else if (l == 0) {
      if (isdigit(str[0]) && isdigit(str[1])) {
        console.log('a' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'a' + str.slice(3))
      }
    } else if (u == 0) {
      if (isLower(str[0]) && isLower(str[1])) {
        console.log('A' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'A' + str.slice(3))
      }
    }
  }
}

const readline = require('readline');
const fs = require('fs')
const rl = readline.createInterface({
   input: process.stdin,
//   input : fs.createReadStream('practice/codeforces/test.in'),
  output: process.stdout
});
num = 0
rl.on('line', str => {
  if (num == 0) {
    num = str
  } else {
    func(str)
  }
});
isdigit = a => a <= 9 && a >= 0
isLower = a => a <= 'z' && a >= 'a'
isUpper = a => a <= 'Z' && a >= 'A'
function func(str) {
  n = 0;
  l = 0;
  u = 0;
  for (char of str) {
    if (isdigit(char)) {
      n += 1
    } else if (isLower(char)) {
      l += 1
    } else if (isUpper(char)) {
      u += 1
    }
  }
  if (n && l && u) {
    console.log(str)
    return;
  }
  if (n == 0 && l == 0) {
    console.log('1a' + str.slice(2))
  } else if (n == 0 && u == 0) {
    console.log('1A' + str.slice(2))
  } else if (l == 0 && u == 0) {
    console.log('aA' + str.slice(2))
  }
  else {
    if (n == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isUpper(str[0]) && isUpper(str[1])) ) {
        console.log('1' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + '1' + str.slice(3))
      }
    }else if (l == 0) {
      if ((isdigit(str[0]) && isdigit(str[1])) ||
        (isUpper(str[0]) && isUpper(str[0]))
      ) {
        console.log('a' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'a' + str.slice(3))
      }
    } else if (u == 0) {
      if ((isLower(str[0]) && isLower(str[1])) ||
      (isdigit(str[0]) && isdigit(str[0]))
      ) {
        console.log('A' + str.slice(1))
      } else {
        console.log(str.slice(0,2) + 'A' + str.slice(3))
      }
    }
  }
}


Given a permutation $$$p$$$ of length $$$n$$$, find its subsequence $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ of length at least $$$2$$$ such that:  $$$|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$$$ is as big as possible over all subsequences of $$$p$$$ with length at least $$$2$$$.  Among all such subsequences, choose the one whose length, $$$k$$$, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some (possibly, zero or all) elements.A permutation of length $$$n$$$ is an array of length $$$n$$$ in which every element from $$$1$$$ to $$$n$$$ occurs exactly once.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the length of the permutation $$$p$$$. The second line of each test case contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_{n}$$$ ($$$1 \le p_i \le n$$$, $$$p_i$$$ are distinct) — the elements of the permutation $$$p$$$. The sum of $$$n$$$ across the test cases doesn't exceed $$$10^5$$$.

For each test case, the first line should contain the length of the found subsequence, $$$k$$$. The second line should contain $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ — its elements. If multiple subsequences satisfy these conditions, you are allowed to find any of them.

NoteIn the first test case, there are $$$4$$$ subsequences of length at least $$$2$$$:  $$$[3,2]$$$ which gives us $$$|3-2|=1$$$.  $$$[3,1]$$$ which gives us $$$|3-1|=2$$$.  $$$[2,1]$$$ which gives us $$$|2-1|=1$$$.  $$$[3,2,1]$$$ which gives us $$$|3-2|+|2-1|=2$$$. So the answer is either $$$[3,1]$$$ or $$$[3,2,1]$$$. Since we want the subsequence to be as short as possible, the answer is $$$[3,1]$$$.

// var lineIdx = 0;
// var readline = () => {
//   var input = ["2", "3", "3 2 1", "4", "1 3 4 2"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var t = readline().split(" ").map(function (x) { return parseInt(x); })[0];

var step = () => {
  var input = readline().split(" ").map(function (x) { return parseInt(x); });
  var n = input[0];

  var res = new Array()

  var row = readline().split(" ").map(function (x) { return parseInt(x); });
  var dir = 0;
  var cur = row[0];
  res.push(cur)

  for (var j = 1; j < row.length; j++) {
    if (dir == 1) {
      if (cur < row[j]) {
      } else {
        res.push(cur)
        dir = -1
      }
    } else if (dir == -1) {
      if (cur > row[j]) {
      } else {
        res.push(cur)
        dir = 1
      }
    } else if(dir == 0){
      if (cur < row[j]) {
        dir = 1;
      } else {
        dir = -1
      }
    }
    cur = row[j]
  }
  res.push(cur)

  print(res.length)
  print(res.join(' '))
}

for (var i2 = 0; i2 < t; i2++) {
  step();
}


Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?

The first line contains an integer n, which is the size of one message (2 ≤ n ≤ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.

On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.

NoteLet's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(0, -1)
  let [n, t] = ils
  n = +n

  const S = t.split(/[!.?]/g).map(s => s.replace(/^\s/, '') + '.').slice(0, -1)
  let mn = 1
  let cml = 0
  for (let i = 0; i < S.length; i++) {
    if (cml + S[i].length <= n) {
      cml += S[i].length + 1
    } else if (S[i].length > n) {
      return console.log('Impossible')
    } else {
      mn++
      cml = S[i].length + 1
    }
  }
  console.log(mn)
})


There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.

The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).

Print $$$t$$$ lines, the answers for each test case.

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));
    var n = params[0];
    var m = params[1];

    var r= params[2];
    var c = params[3];

    var dist = 0;

    if(dist < (r-1)+(c-1))
    {
        dist = (r-1)+(c-1);
    }

    if(dist < Math.abs(r-n)+Math.abs(c-1))
    {
        dist = Math.abs(r-n)+Math.abs(c-1);
    }

    if(dist < Math.abs(r-n)+Math.abs(c-m))
    {
        dist = Math.abs(r-n)+Math.abs(c-m);
    }

    if(dist < Math.abs(r-1)+Math.abs(c-m))
    {
        dist = Math.abs(r-1)+Math.abs(c-m);
    }

    print(dist);

}

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

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const T=Number(readLine());
    for (let  i = 0; i < T; i ++) {
        const line = readLine();
        const n = Number(line.split(" ")[0]);
        const m = Number(line.split(" ")[1]);
        const r = Number(line.split(" ")[2]);
        const c = Number(line.split(" ")[3]);
        console.log(Math.max(Math.abs(r-1), Math.abs(r-n)) + Math.max(Math.abs(c-1), Math.abs(c-m)));
    }

}

const solve = (n, m, r, c) => {
    let topLeft = Math.abs(0 - r + 1) + Math.abs(0 - c + 1);
    let topRight = Math.abs(0 - r + 1) + Math.abs(m - 1 - c + 1);
    let bottomLeft = Math.abs(n - 1 - r + 1) + Math.abs(0 - c + 1);
    let bottomRight = Math.abs(n - 1 - r + 1) + Math.abs(m - 1 - c + 1);
    console.log(Math.max(topLeft, topRight, bottomLeft, bottomRight));
};

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

main()


You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.

The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.

On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters. If the answer consists of zero characters, output «-» (a minus sign).

NoteIn the first example strings a and b don't share any symbols, so the longest string that you can get is empty.In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = a.length - ai--;
        } else {
            ai--;
        }
    }

    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > a.length){

            si++;
            continue;
        } else {
            if(pi+1+b.length-si > max && pi+1+b.length-si <=b.length){
                max = pi+1+b.length-si;

                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = a.length - ai--;
        } else {
            ai--;
        }
    }

    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > a.length){

            si++;
            continue;
        } else {
            if(p[pi] + s[si] > max){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    si = b.length
    while(pi < b.length){
        if(p[pi] + s[si] > max && p[pi] + s[si] <= a.length){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = a.length - ai--;
        } else {
            ai--;
        }
    }
     for(var i=0;i<b.length;i++){
        s[i]++;
    }
    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > a.length){

            si++;
            continue;
        } else {
            if(p[pi] + s[si] > max){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = a.length - ai--;
        } else {
            ai--;
        }
    }

    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > a.length){

            si++;
            continue;
        } else {
            if(pi+1+b.length-si > max){
                max = pi+1+b.length-si;

                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    si = b.length

    while(pi < b.length){
        if(p[pi] + s[si] > max && p[pi] + s[si] <= a.length){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = ai--;
        } else {
            ai--;
        }
    }
     for(var i=0;i<b.length;i++){
        s[i]++;
    }
    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > b.length){

            si++;
            continue;
        } else {
            if(p[pi] + s[si] > max){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = a.length - ai--;
        } else {
            ai--;
        }
    }

    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > a.length){

            si++;
            continue;
        } else {
            if(p[pi] + s[si] > max){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    while(pi < b.length){
        if(p[pi] + s[si] > max && p[pi] + s[si] <= a.length){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()

function main() {
    var a = readline();
    var b = readline();

    var p=[];
    var ai = 0;
    for(var i =0;i<b.length;){
        if(ai == a.length){
            p[i++] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]) {
            p[i++] = ai++;
        } else {
            ai++;
        }
    }
    for(var i=0;i<b.length;i++){
        p[i]++;
    }

    var s = [];
    var ai = a.length-1;
    for(var i=b.length-1;i>=0;){
        if(ai < 0){
            s[i--] = Number.MAX_VALUE;
        } else if(b[i] == a[ai]){
            s[i--] = a.length - ai--;
        } else {
            ai--;
        }
    }

    p[-1] = 0;
    s[b.length] = 0;
    var si = 0;
    var pi = -1;
    var max = -1;
    var res = "-"
    var siRes;
    var piRes
    while(si <= b.length && pi < b.length){
        if(p[pi] + s[si] > a.length){

            si++;
            continue;
        } else {
            if(p[pi] + s[si] > max){
                max = p[pi] + s[si];
                siRes = si;
                piRes = pi;
            }
            pi++;
        }
    }
    if(max > 0){
        var res = ""
        for(var i=0;i<=piRes;i++){
            res += b[i];
        }
        for(var i=siRes;i<b.length;i++){
            res += b[i];
        }
        print(res)
    } else {
        print(res);
    }
}

main()


Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types:  Replace $$$i$$$-th element in the array with integer $$$x$$$.  Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query:   If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$) — position of replaced element and it's new value.  If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$) — new value of each element in the array.

Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.

NoteConsider array from the example and the result of performing each query:  Initial array is $$$[1, 2, 3, 4, 5]$$$.  After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$.  After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$.  After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$.  After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$.  After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var _a = readline().split(' ').map(function (v) { return +v; }), n = _a[0], q = _a[1];
var a = readline().split(' ').map(function (v) { return +v; });
var sum = a.reduce(function (a, b) { return a + b; });
var m = new Map();
for (var i = 0; i < n; i++)
    m.set(i, a[i]);
var cur = 0;
for (var i = 0; i < q; i++) {
    var b = readline().split(' ').map(function (v) { return +v; });
    if (b[0] === 1) {
        var i_1 = b[1] - 1;
        var v = b[2];
        if (m.has(i_1)) {
            sum += v - m.get(i_1);
        }
        else {
            sum += v - cur;
        }
        m.set(i_1, v);
    }
    else {
        cur = b[1];
        m = new Map();
        sum = cur * n;
    }
    print(sum);
}

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

    main(lines);
})

	function main(line){
		let [n,q] = line[0].split(' ').map(x=>parseInt(x));
		let arr = line[1].split(' ').map(x=>parseInt(x));
		let sum = arr.reduce((prev,cur) => prev+cur,0);
//		let set = new Set();
		let set = new Set(Array.from(Array(n).keys()));
		let T2;
		for(let i=2;i<q+2;i++){
			let [t, ...v] = line[i].split(' ').map(x=>parseInt(x));
			if(t==1) {
				v[0]--;
				if(set.has(v[0])){
					sum+=v[1]-arr[v[0]];
					arr[v[0]] = v[1];
				} else {
					sum+=v[1]-T2;
					arr[v[0]] = v[1];
					set.add(v[0]);
				}
			} else {
				set.clear();
				T2 = v[0];
				sum = T2*n;
			}
			console.log(sum);
		}
	}

//{ Driver Code Starts
//Initial Template for javascript
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let t = readLine().split(' ').map(string => {return parseInt(string)});
    let n=t[0],q=t[1];
    let a = readLine().split(' ').map(string => {return parseInt(string)});
    let m = {},sum=0;
    // sum = a.reduce((a, b) => a + b, 0);
    for(let i=0;i<n;i++){
        m[i+1]=a[i];
        sum+=a[i];
    }
    let flag=0,clearVal=0;
    for(let i=0;i<q;i++)
    {
        t = readLine().split(' ').map(string => {return parseInt(string)});
        if(t[0] == 1){
            if(m[t[1]]){
                sum-=m[t[1]];
                m[t[1]] = t[2];
                sum+=t[2];
            }else{
                sum-=clearVal;
                m[t[1]] = t[2];
                sum+=t[2];
            }
        }else{
            flag = 1;
            sum = n*t[1];
            clearVal = t[1];
            m = {};
        }
        console.log(sum);
    }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
var T = 1;//readline();
for(var qe=1;qe<=T;qe++) {
  var [n, q] = readline().split(' ').map((x) => parseInt(x));
  //n = parseInt(n);
  var a = readline().split(' ').map((x) => parseInt(x));
  var sum = 0;
  var cnt = []
  for(var i=0;i<n;i++) {
    sum += a[i];
    cnt[i] = 0;
  }
  //console.log(sum)
  var everything = -1, everything_val = 0;
  for(var i=0;i<q;i++) {
    var s = readline().split(' ').map((x) => parseInt(x));
    if(s[0] == 1) {
      if(cnt[s[1]-1] > everything) {
        sum += (s[2]-a[s[1]-1])
        a[s[1]-1] = s[2]
        cnt[s[1]-1] = i+1;
      } else {
        sum += (s[2]-everything_val)
        a[s[1]-1] = s[2];
        cnt[s[1]-1] = i+1;
      }
    } else {
      sum = s[1]*n;
      everything = i+1;
      everything_val = s[1];
    }
    console.log(sum)
    //fs.appendFileSync('output.txt', sum+'\r\n');
  }
  //console.log(ans);

  //console.log(ans.join(' '))
  //fs.appendFileSync('output.txt', ans.join(' ')+'\r\n');

}
//

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    // let t = parseInt(readLine());
    // while (t-- > 0) {
    solve();
    // }
}
function solve() {
    let [n, q] = readLine().split(" ").map(i => parseInt(i));
    let arr = readLine().split(" ").map(i => parseInt(i));
    let sum = arr.reduce((a, c) => a + c, 0);
    let filled = -1;
    let map = new Map();
    while (q--) {
        let query = readLine().split(" ").map(i => parseInt(i));
        if (query.length == 3) {
            let temp = 0;
            if (map.has(query[1])) {
                temp = map.get(query[1]);
            } else {
                temp = filled != -1 ? filled : arr[query[1] - 1];
            }
            arr[query[1] - 1] = query[2];
            map.set(query[1], query[2]);
            sum -= temp;
            sum += arr[query[1] - 1];
        } else {
            filled = query[1];
            map.clear();
            sum = query[1] * arr.length;
        }
        console.log(sum);
    }
}

'use strict';

var readline = require('readline');

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

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

function solve(n, m, a, b) {
  let sum = a.reduce((a, b) => a + b, 0),
      nums = new Array(n).fill(0),
      flag = false,
      newNum = -1,
      ops = new Set();
  const res = [];
  for (let [t, i, x] of b) {
    if (t === 1) {
      i--;
      let num = -1;
      if (ops.has(i)) {
        num = nums[i];
      } else {
        if (flag) {
          num = newNum;
        } else {
          num = a[i];
        }
      }
      ops.add(i);
      sum -= num - x;
      nums[i] = x;
    } else {
      newNum = i;
      sum = n * i;
      ops.clear();
      if (!flag) flag = true;
    }
    res.push(sum);
  }
  console.log(res.join('\n'));
}

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

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

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    let sum = 0
    let value = {}
    let same
    arr.forEach((x, i) => {
        value[i + 1] = x
        sum += x
    })
    return qs.map(([t, i, x]) => {
        if (t == 1) {
            const prev = (i in value) ? value[i] : same
            sum += x - prev
            value[i] = x
        } else {
            x = i
            //
            value = {}
            same = x
            sum = n * x
        }
        return sum
    }).join('\n')
}

let obj = {};
let sum = 0;
let flag = 1;
let arr ;
const solve = (q)=>{
     if(q[0]===2) {
          sum = arr.length*q[1];
          obj = {};
          obj["all"] = q[1];
          flag = 0;
     }
     else{
          if(flag){
               if(!obj[q[1]-1]) sum=sum-arr[q[1]-1] + q[2];
               else sum=sum-obj[q[1]-1] + q[2];
               obj[q[1]-1] = q[2];
          }
          else{
               if(!obj[q[1]-1])sum=sum-obj["all"] +q[2];
               else sum=sum-obj[q[1]-1] + q[2];
               obj[q[1]-1] = q[2];
          }
     }
     console.log(sum);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let [n,t] = readline().trim().split(" ").map(cur=>parseInt(cur));
  arr =  readline().trim().split(" ").map(cur=>parseInt(cur));
  sum = arr.reduce((s,c)=>s+c,0);
  for (let i = 0; i < t; i++) {
       let q = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(q);
  }
}
main();

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
];

// SOLUTION:
IS_MULTITEST = false;

class SegmentTree {
    constructor(arr){
        this.n = arr.length;
        this.l = null;
        this.r = null;
        this.sum = 0;
        this.toPush = null;
        this.build(arr);
    }
    getMiddle(){
        return Math.floor(this.n/2);
    }
    build(arr){
        if (arr.length==0)
            return;
        if (arr.length==1){
            this.sum = arr[0];
            return;
        }
        let m = this.getMiddle();
        let sum = 0;
        let leftArr = arr.slice(0, m);
        if (leftArr.length){
            this.l = new SegmentTree(leftArr);
            sum += this.l.sum;
        }
        let rightArr = arr.slice(m);
        if (rightArr.length){
            this.r = new SegmentTree(rightArr);
            sum += this.r.sum;
        }
        this.sum = sum;
    }
    push(){
      if (this.toPush==null)
        return;
      this.sum = this.n*this.toPush;
      if (this.r){
        this.r.toPush = this.toPush;
      }
      if (this.l){
        this.l.toPush = this.toPush;
      }
      this.toPush = null;
    }
    setAll(val){
      this.toPush = val;
    }
    set(i, val){
      this.push();
        if (this.n==1)
        {
            this.sum = val;
            return;
        }
        let m = this.getMiddle();
        if (i<m)
            this.l.set(i, val);
        else
            this.r.set(i-m, val);
        if (this.l)
          this.l.push();
        if (this.r)
          this.r.push();
        this.sum = (this.l ? this.l.sum : 0) +
            (this.r ? this.r.sum : 0);
    }
    sumRange(l, r){
        this.push();
        if (l==0 && r==this.n-1)
            return this.sum;
        let m = this.getMiddle();
        let sum = 0;
        if (l<m)
            sum += this.l.sumRange(l, Math.min(m-1, r));
        if (m<=r)
            sum += this.r.sumRange(Math.max(l-m, 0), r-m);
        return sum;
    }
}
const calc = (testN)=>{
  // READING:
  let [n, q] = ra();
  let A = ra();
  LT({n, A});
  // PROCESSING:
  let st = new SegmentTree(A);
  let ans = '';

  while (q--){
    let [t, a, b] = ra();
    if (t==1){
      let i = a, x = b;
      st.set(i-1, x);
      ans += st.sumRange(0, n-1)+'\n';
    } else {
      let x = a;
      st.setAll(x);
      ans += st.sumRange(0, n-1)+'\n';
    }
  }
  return ans;
};

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

    main(lines);
})

	function main(line){
		let [n,q] = line[0].split(' ').map(x=>parseInt(x));
		let arr = line[1].split(' ').map(x=>parseInt(x));
		let sum = arr.reduce((prev,cur) => prev+cur,0);
//		let set = new Set();
		let set = new Set(Array.from(Array(10).keys()));
		let T2;
		for(let i=2;i<q+2;i++){
			let [t, ...v] = line[i].split(' ').map(x=>parseInt(x));
			if(t==1) {
				v[0]--;
				if(set.has(v[0])){
					sum+=v[1]-arr[v[0]];
					arr[v[0]] = v[1];
				} else {
					sum+=v[1]-T2;
					arr[v[0]] = v[1];
					set.add(v[0]);
				}
			} else {
				set.clear();
				T2 = v[0];
				sum = T2*n;
			}
			console.log(sum);
		}
	}

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

    main(lines);
})
	function main(line){
		let [n,q] = line[0].split(' ').map(x=>parseInt(x));
		console.log(line);
		console.log(line[0], n,q);
	}

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

    main(lines);
})
	function main(line){
		let [n,q] = line[0].split(' ').map(x=>parseInt(x));
		console.log(n,q);
	}

//{ Driver Code Starts
//Initial Template for javascript
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let t = readLine().split(' ').map(string => {return parseInt(string)});
    let n=t[0],q=t[1];
    let a = readLine().split(' ').map(string => {return parseInt(string)});
    let m = {},sum=0;
    // sum = a.reduce((a, b) => a + b, 0);
    for(let i=0;i<q;i++){
        m[i+1]=a[i];
        sum+=a[i];
    }
    let flag=0,clearVal=0;
    for(let i=0;i<q;i++)
    {
        t = readLine().split(' ').map(string => {return parseInt(string)});
        if(t[0] == 1){
            if(m[t[1]]){
                sum-=m[t[1]];
                m[t[1]] = t[2];
                sum+=t[2];
            }else{
                sum-=clearVal;
                m[t[1]] = t[2];
                sum+=t[2];
            }
        }else{
            flag = 1;
            sum = n*t[1];
            clearVal = t[1];
            m = {};
        }
        console.log(sum);
    }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
var T = 1;//readline();
for(var qe=1;qe<=T;qe++) {
  var [n, q] = readline().split(' ').map((x) => parseInt(x));
  //n = parseInt(n);
  var a = readline().split(' ').map((x) => parseInt(x));
  var sum = 0;
  var cnt = []
  for(var i=0;i<n;i++) {
    sum += a[i];
    cnt[i] = 0;
  }
  //console.log(sum)
  var everything = -1, everything_val = 0;
  for(var i=0;i<q;i++) {
    var s = readline().split(' ').map((x) => parseInt(x));
    if(s[0] == 1) {
      if(cnt[s[1]] > everything) {
        sum += (s[2]-a[s[1]-1])
        a[s[1]-1] = s[2]
        cnt[s[1]-1]++;
      } else {
        sum += (s[2]-everything_val)
        a[s[1]-1] = s[2];
        cnt[s[1]-1]++;
      }
    } else {
      sum = s[1]*n;
      everything = i+1;
      everything_val = s[1];
    }
    console.log(sum)
    //fs.appendFileSync('output.txt', sum+'\r\n');
  }
  //console.log(ans);

  //console.log(ans.join(' '))
  //fs.appendFileSync('output.txt', ans.join(' ')+'\r\n');

}
//

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
var T = 1;//readline();
for(var qe=1;qe<=T;qe++) {
  var [n, q] = readline().split(' ').map((x) => parseInt(x));
  //n = parseInt(n);
  var a = readline().split(' ').map((x) => parseInt(x));
  var sum = 0;
  var cnt = []
  for(var i=0;i<n;i++) {
    sum += a[i];
    cnt[i] = 0;
  }
  console.log(sum)
  var everything = -1, everything_val = 0;
  for(var i=0;i<q;i++) {
    var s = readline().split(' ').map((x) => parseInt(x));
    if(s[0] == 1) {
      if(cnt[s[1]] > everything) {
        sum += (s[2]-a[s[1]-1])
        a[s[1]-1] = s[2]
        cnt[s[1]-1]++;
      } else {
        sum += (s[2]-everything_val)
        a[s[1]-1] = s[2];
        cnt[s[1]-1]++;
      }
    } else {
      sum = s[1]*n;
      everything = i+1;
      everything_val = s[1];
    }
    console.log(sum)
    //fs.appendFileSync('output.txt', sum+'\r\n');
  }
  //console.log(ans);

  //console.log(ans.join(' '))
  //fs.appendFileSync('output.txt', ans.join(' ')+'\r\n');

}
//

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    // let t = parseInt(readLine());
    // while (t-- > 0) {
    solve();
    // }
}
function solve() {
    let [n, q] = readLine().split(" ").map(i => parseInt(i));
    let arr = readLine().split(" ").map(i => parseInt(i));
    let sum = arr.reduce((a, c) => a + c, 0);
    let filled = -1;
    while (q--) {
        let query = readLine().split(" ").map(i => parseInt(i));
        if (query.length == 3) {
            let temp = filled != -1 ? filled : arr[query[1] - 1];
            arr[query[1] - 1] = query[2];
            sum -= temp;
            sum += arr[query[1] - 1];
        } else {
            filled = query[1];
            sum = query[1] * arr.length;
        }
        console.log(sum);
    }
}

'use strict';

var readline = require('readline');

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

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

function solve(n, m, a, b) {
  let sum = a.reduce((a, b) => a + b, 0),
      nums = new Array(n).fill(0),
      flag = false,
      newNum = -1,
      ops = new Set();
  const res = [];
  for (let [t, i, x] of b) {
    if (t === 1) {
      i--;
      let num = -1;
      if (ops.has(i)) {
        num = nums[i];
      } else {
        if (flag) {
          num = newNum;
        } else {
          num = a[i];
        }
      }
      sum -= num - x;
      nums[i] = x;
    } else {
      newNum = i;
      sum = n * i;
      ops.clear();
      flag = true;
    }
    res.push(sum);
  }
  console.log(res.join('\n'));
}

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

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


Andryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?

The first line contains the single integer n (1 ≤ n ≤ 105) — the number of sock pairs. The second line contains 2n integers x1, x2, ..., x2n (1 ≤ xi ≤ n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi. It is guaranteed that Andryusha took exactly two socks of each pair.

Print single integer — the maximum number of socks that were on the table at the same time.

NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows:   Initially the table was empty, he took out a sock from pair 2 and put it on the table.  Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table.  Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe.  Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table.  Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe.  Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe.  Thus, at most two socks were on the table at the same time.

var max_socks = 0;
var curr_socks_on_table = 0;
var is_sock_taken = {};

readline();
readline().split(' ').map(function(x){

    if(is_sock_taken[x])
        curr_socks_on_table--;
    else
        curr_socks_on_table++;

    is_sock_taken[x] = true;
    max_socks = Math.max(max_socks, curr_socks_on_table);
});

print(max_socks);

var onTable = [],
    max = 0,
    kx = 0;
var total = +readline();
var socks = readline().split(' ').forEach(sock => {
    if(onTable[sock]) {
        onTable[sock] = 0;
        max --;
    } else {
        onTable[sock] = 1;
        max ++;
    }

    kx = Math.max(max, kx);
})

write(kx)

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

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

  const arr = d.split(' ').map(Number);
  const obj = {};
  let ans = 0;
  let count = 0;

  for (let i = 0; i < arr.length; i++) {
    if (obj[arr[i]]) {
      delete obj[arr[i]];
      count--;
    }
    else {
      obj[arr[i]] = true;
      count++;
    }

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

  console.log(ans);

  c++;
});

var n = parseInt(readline());
	var socks=[];
	socks = readline().split(" ").map(x=>+x);
	var a=[];
	var l = 0;
	var maximum = 0;
	for(var i = 0; i < 2*n; i++){
		if(a[socks[i]]){
			l --;
		}
		else{
			l++;
			a[socks[i]] = true;
		}
		maximum = Math.max(maximum,l);
	}
	print(maximum);

readline()
var tab = readline().split(' ').map(x=>+x)
  , l = tab.length
  , socks = []
  , n = 0
  , max = 0

for (var i = 0 ; i < l ; i++) {
  socks[tab[i]] ? n-- : (n++, socks[tab[i]] = true)
  n > max && (max = n)
}

print(max)

var count = readline();

var max = 0;
var table = { length: 0 };
var socks = readline()
  .split(' ')
  .forEach(function(sock) {
    if (table[sock] == 1) {
      table.length--;
    } else {
      table[sock] = 1;
      table.length++;
    }
    max = max < table.length ? table.length : max;
  });

print(max);

var n = +readline(),
    x = readline().split(' ').map(v => +v),
    u = new Array(100000), s = 0, max = 0;

for(var i = 0; i<n*2; i++) {
    if(u[x[i]]) s--;
    else s++;
    u[x[i]] = true;
    max = Math.max(max, s);
}
print(max);

var n = parseInt(readline());
var x = readline().split(' ').map(function(x) {
  return parseInt(x);
});
var table = [];
var s = 0;
var ms = -1;
for(var i = 0; i < 2 * n; i += 1) {
  if(table[x[i]]) {
    table[x[i]] = undefined;
    s -= 1;
  } else {
    table[x[i]] = 1;
    s += 1;
    ms = s > ms ? s : ms;
  }
}
print(ms);

readline();
var order = readline().split(' ');
var table = {};
var maxSocksOnTable = 0;
var currentCount = 0;
for (var i=0; i<order.length; i++) {
  var sock = 's' + order[i];
  if (table[sock] !== undefined) {
    delete table[sock];
    currentCount -= 1;
  } else {
    table[sock] = true;
    currentCount += 1;
  }
  if (currentCount > maxSocksOnTable) {
    maxSocksOnTable = currentCount;
  }
}
print(maxSocksOnTable);

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

switch(n) {

    case 1:
        print(1);
        break;
    case 3:
        print(2);
        break;
    case 5:
        print(5);
        break;
    default:
        break;
}

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

switch(n) {

    case 1:
        print(1);
        break;
    case 3:
        print(2);
        break;
    case 5:
        print(5);
        break;
    default:
        print(socks);
        break;
}

var max_socks = 0;
var table = [];

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

print(max_socks);

var n = parseInt(readline());
	var socks=[];
	socks = readline().split(" ").map(x=>+x);
	var a=[];
	var l = 0;
	var maximum = 0;
	for(var i = 0; i < n; i++){
		if(a[socks[i]]){
			l --;
		}
		else{
			l++;
			a[socks[i]] = true;
		}
		maximum = Math.max(maximum,l);
	}
	print(maximum);

readline();
var order = readline().split(' ');
var table = {};
var maxSocksOnTable = 0;
for (var i=0; i<order.length; i++) {
  var sock = 's' + order[i];
  //var indexOfSock = table.indexOf(sock);
  if (table[sock] !== undefined) {
    delete table[sock];
    maxSocksOnTable -= 1;
  } else {
    table[sock] = true;
    maxSocksOnTable += 1;
  }
}
print(maxSocksOnTable);