Everybody knows that the $$$m$$$-coder Tournament will happen soon. $$$m$$$ schools participate in the tournament, and only one student from each school participates.There are a total of $$$n$$$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $$$k$$$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le m, k \le n$$$) — the total number of students, the number of schools and the number of the Chosen Ones. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ denotes the power of $$$i$$$-th student. The bigger the power, the stronger the student. The third line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le m$$$), where $$$s_i$$$ denotes the school the $$$i$$$-th student goes to. At least one student studies in each of the schools.  The fourth line contains $$$k$$$ different integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \le c_i \le n$$$)  — the id's of the Chosen Ones.

Output a single integer  — the minimal number of schools to be made up by Arkady so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

NoteIn the first example there's just a single Chosen One with id $$$3$$$. His power is equal to $$$3$$$, but in the same school $$$1$$$, there's a student with id $$$5$$$ and power $$$6$$$, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be $$$4$$$) for the Chosen One, Technogoblet would select students with ids $$$2$$$ (strongest in $$$3$$$), $$$5$$$ (strongest in $$$1$$$), $$$6$$$ (strongest in $$$2$$$) and $$$3$$$ (strongest in $$$4$$$).In the second example, you can change the school of student $$$3$$$ to the made-up $$$5$$$ and the school of student $$$4$$$ to the made-up $$$6$$$. It will cause the Technogoblet to choose students $$$8$$$, $$$7$$$, $$$6$$$, $$$5$$$, $$$3$$$ and $$$4$$$.

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

var inputs = [];

let bKey = (vl) => {
    return vl.val + ":" + vl.idx;
}

function main() {
    const [n, m, kk] = inputs[0].split(" ").map(_ => parseInt(_));
    const power = inputs[1].split(" ").map(_ => parseInt(_));
    const school = inputs[2].split(" ").map(_ => parseInt(_));
    const k = inputs[3].split(" ").map(_ => parseInt(_));

    const mode = {};

    school.forEach((v, idx) => {
        if (mode[v] === undefined) {
            mode[v] = [];
        }
        mode[v].push({
            idx: idx + 1,
            val: power[idx]
        });
    });
    Object.keys(mode).forEach( _ => {
        mode[_].sort((v1, v2) => {
            if(v1.val > v2.val) return 1;
            if(v1.val < v2.val) return -1;
            return 0;
        })
    })
    let vis = {};
    let res = 0;
    k.forEach(idx => {
        let node = {
            idx: idx,
            val: power[idx - 1]
        };

        let sCount = false;
        let count = 0;
        let iddx = -1;
        let exist = mode[school[idx - 1]].reduce((tot, v) => {
            iddx++;
            if(v.val === node.val && v.idx === node.idx) {
                return Math.max(tot, iddx);
            }
            return tot;
        }, -1);
        exist = exist !== -1 && exist != mode[school[idx - 1]].length - 1;

        res += exist;
    });

    console.log(res);
}

readline.on('line', (input) => { inputs.push(input); });
readline.on('close', main)

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

var inputs = [];

let bKey = (vl) => {
    return vl.val + ":" + vl.idx;
}

function main() {
    const [n, m, kk] = inputs[0].split(" ").map(_ => parseInt(_));
    const power = inputs[1].split(" ").map(_ => parseInt(_));
    const school = inputs[2].split(" ").map(_ => parseInt(_));
    const k = inputs[3].split(" ").map(_ => parseInt(_));

    const mode = {};

    school.forEach((v, idx) => {
        if (mode[v] === undefined) {
            mode[v] = [];
        }
        mode[v].push({
            idx: idx + 1,
            val: power[idx]
        });
    });

    let vis = {};
    let res = 0;
    k.forEach(idx => {
        let node = {
            idx: idx,
            val: power[idx - 1]
        };

        let sCount = false;
        let count = 0;
        mode[school[idx - 1]].forEach((val, idx) => {
            if (val.idx === node.idx && val.val === node.val) {
                sCount = true;
            } else if (sCount && vis[bKey(val)] === undefined) {
                vis[bKey(val)] = true;
                count++;
            }
        });
        res += count;
    });

    console.log(res);
}

readline.on('line', (input) => {
    inputs.push(input);
});
readline.on('close', main)

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

var inputs = [];

let bKey = (vl) => {
    return vl.val + ":" + vl.idx;
}

function main() {
    const [n, m , kk] = inputs[0].split(" ").map(_ => parseInt(_));
    const power = inputs[1].split(" ").map(_ => parseInt(_));
    const school = inputs[2].split(" ").map(_ => parseInt(_));
    const k = inputs[3].split(" ").map(_ => parseInt(_));

    const mode = {};

    school.forEach((v, idx) => {
        if(mode[v] === undefined) {
            mode[v] = [];
        }
        mode[v].push({idx: idx + 1, val: power[idx]});
    });

    let vis = {};
    let res = 0;
    k.forEach(idx => {
        let node = {idx: idx, val: power[idx - 1]};
        let sCount = false;
        let count = 0;
        // console.log(`school ${school[idx - 1]}`, node, vis);
        mode[school[idx - 1]].forEach((val, idx) => {
            // console.log("---->", val, vis[bKey(val)])
            if(val.idx === node.idx && val.val === node.val) {
                sCount = true;
            }else if(sCount && vis[bKey(val)] === undefined) {
                vis[bKey(val)] = true;
                count++;
            }
        });
        res += count;
    });

    console.log(res);
}

readline.on('line', (input) => { inputs.push(input); });
readline.on('close', main)

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

var inputs = [];

let bKey = (vl) => {
    return vl.val + ":" + vl.idx;
}

function main() {
    const [n, m, kk] = inputs[0].split(" ").map(_ => parseInt(_));
    const power = inputs[1].split(" ").map(_ => parseInt(_));
    const school = inputs[2].split(" ").map(_ => parseInt(_));
    const k = inputs[3].split(" ").map(_ => parseInt(_));

    const mode = {};

    school.forEach((v, idx) => {
        if (mode[v] === undefined) {
            mode[v] = [];
        }
        mode[v].push({
            idx: idx + 1,
            val: power[idx]
        });
    });
    Object.keys(mode).forEach( _ => {
        mode[_].sort((v1, v2) => {
            if(v1.val > v2.val) return 1;
            if(v1.val < v2.val) return -1;
            return 0;
        })
    })
    let vis = {};
    let res = 0;
    k.forEach(idx => {
        let node = {
            idx: idx,
            val: power[idx - 1]
        };

        let sCount = false;
        let count = 0;
        mode[school[idx - 1]].forEach((val, idx) => {
            if (val.idx === node.idx && val.val === node.val) {
                sCount = true;
            } else if (sCount && vis[bKey(val)] === undefined) {
                vis[bKey(val)] = true;
                count++;
            }
        });
        res += count;
    });

    console.log(res);
}

readline.on('line', (input) => { inputs.push(input); });
readline.on('close', main)

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

var inputs = [];

let bKey = (vl) => {
    return vl.val + ":" + vl.idx;
}

function main() {
    const [n, m , kk] = inputs[0].split(" ").map(_ => parseInt(_));
    const power = inputs[1].split(" ").map(_ => parseInt(_));
    const school = inputs[2].split(" ").map(_ => parseInt(_));
    const k = inputs[3].split(" ").map(_ => parseInt(_));

    const mode = {};

    school.forEach((v, idx) => {
        if(mode[v] === undefined) {
            mode[v] = [];
        }
        mode[v].push({idx: idx + 1, val: power[idx]});
    });

    let vis = {};

    k.forEach(idx => {
        let node = {idx: idx, val: power[idx - 1]};

        let sCount = false;
        let count = 0;
        mode[school[idx - 1]].forEach((val, idx) => {
            if(val.idx === node.idx && val.val === node.val) {
                sCount = true;
            }else if(sCount && vis[bKey(val)] === undefined) {
                vis[bKey(val)] = true;
                count++;
            }
        });
        vis[bKey(node)] = true;
        console.log(count);
    });
}

readline.on('line', (input) => { inputs.push(input); });
readline.on('close', main)

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

var inputs = [];

let bKey = (vl) => {
    return vl.val + ":" + vl.idx;
}

function main() {
    const [n, m , kk] = inputs[0].split(" ").map(_ => parseInt(_));
    const power = inputs[1].split(" ").map(_ => parseInt(_));
    const school = inputs[2].split(" ").map(_ => parseInt(_));
    const k = inputs[3].split(" ").map(_ => parseInt(_));

    const mode = {};

    school.forEach((v, idx) => {
        if(mode[v] === undefined) {
            mode[v] = [];
        }
        mode[v].push({idx: idx + 1, val: power[idx]});
    });

    let vis = {};
    let res = 0;
    k.forEach(idx => {
        let node = {idx: idx, val: power[idx - 1]};

        let sCount = false;
        let count = 0;
        mode[school[idx - 1]].forEach((val, idx) => {
            if(val.idx === node.idx && val.val === node.val) {
                sCount = true;
            }else if(sCount && vis[bKey(val)] === undefined) {
                vis[bKey(val)] = true;
                count++;
            }
        });
        vis[bKey(node)] = true;
        res += count;
    });

    console.log(res);
}

readline.on('line', (input) => { inputs.push(input); });
readline.on('close', main)


You have given tree consist of $$$n$$$ vertices. Select a vertex as root vertex that satisfies the condition below.  For all vertices $$$v_{1}$$$ and $$$v_{2}$$$, if $$$distance$$$($$$root$$$, $$$v_{1}$$$) $$$= distance$$$($$$root$$$, $$$v_{2})$$$ then $$$degree$$$($$$v_{1}$$$) $$$= degree$$$($$$v_{2}$$$), where $$$degree$$$ means the number of vertices connected to that vertex, and $$$distance$$$ means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of vertices. Each of the next $$$n-1$$$ lines contains two integers $$$v_{i}$$$ and $$$u_{i}$$$ ($$$1 \le v_{i} \lt u_{i} \le n$$$) — it means there is an edge exist between $$$v_{i}$$$ and $$$u_{i}$$$. It is guaranteed that the graph forms tree.

If there is such root vertex exists, print any of them. Otherwise, print $$$-1$$$.

NoteThis is the picture for the first example. $$$1$$$, $$$5$$$, $$$7$$$ also can be a valid answer.  This is the picture for the second example. You can see that it's impossible to find such root vertex.

const readline = require('readline');
const rl = readline.createInterface(
    {
        input: process.stdin,
    }
);
const lines = [];
rl.on('line', x => lines.push(x));
rl.on('close', () => {
    const n = parseInt(lines[0], 10);
    const nodes = Array.from({length: n}, (_, i) => i + 1);
    if (n === 1) {
        console.log(1);
        return;
    }

    const edge = {};
    for (let i = 1; i < n; i++) {
        const [x, y] = lines[i].split(' ').map(a => parseInt(a));
        if (!edge[x]) {
            edge[x] = [];
        }
        edge[x].push(y);
        if (!edge[y]) {
            edge[y] = [];
        }
        edge[y].push(x);
    }

    let parent;
    let depth;
    const bfs = (initX, initP) => {
        parent = {};
        depth = {};
        parent[initX] = -1;
        depth[initX] = 0;
        if (initP !== undefined) {
            parent[initX] = initP;
        }
        const queue = [initX];
        let top = 0;
        while (top < queue.length) {
            const x = queue[top];
            top += 1;
            for (const target of edge[x]) {
                if (target !== parent[x]) {
                    parent[target] = x;
                    depth[target] = depth[x] + 1;
                    queue.push(target);
                }
            }
        }
    };

    const check = (initX) => {
        bfs(initX);
        const degrees = {};
        for (const x of nodes) {
            const d = depth[x];
            if (degrees[d] === undefined) {
                degrees[d] = edge[x].length;
            } else if (edge[x].length !== degrees[d]) {
                return false;
            }
        }

        return true;
    };

    // find mid
    bfs(1);
    let d = Math.max(...Object.values(depth));
    const v1 = nodes.find(x => depth[x] === d);
    bfs(v1);
    d = Math.max(...Object.values(depth));
    const v2 = nodes.find(x => depth[x] === d);
    // check mid
    let mid = v2;
    for (let i = d; i !== Math.floor(d/2); i--, mid = parent[mid]) {}
    if (check(mid)) {
        console.log(mid);
        return;
    }
    // check leaf2
    const degrees = {};
    const leader = {};
    for (const x of nodes) {
        const d = depth[x];
        if (degrees[d] === undefined) {
            degrees[d] = edge[x].length;
            leader[d] = x;
        } else if (edge[x].length !== degrees[d]) {
            const targets = [leader[d], x];
            const p2 = parent;
            for (const node of targets) {
                bfs(node, p2[node]);
                let d = Math.max(...Object.values(depth));
                const v = nodes.find(x => depth[x] === d);
                if (check(v)) {
                    console.log(v);
                    return;
                }
            }
            break;
        }
    }

    console.log(-1);
})

const readline = require('readline');
const rl = readline.createInterface(
    {
        input: process.stdin,
    }
);
const lines = [];
rl.on('line', x => lines.push(x));
rl.on('close', () => {
    const n = parseInt(lines[0], 10);
    if (n === 1) {
        console.log(1);
        return;
    }

    const edge = {};
    for (let i = 1; i < n; i++) {
        const [x, y] = lines[i].split(' ').map(a => parseInt(a));
        if (!edge[x]) {
            edge[x] = [];
        }
        edge[x].push(y);
        if (!edge[y]) {
            edge[y] = [];
        }
        edge[y].push(x);
    }

    const p = {};
    const bfs = (initX) => {
        const queue = [[initX, -1, 0]];
        let top = 0;
        let result = [initX, 0];
        while (top < queue.length) {
            const [x, parent, depth] = queue[top];
            p[x] = parent;
            top += 1;
            if (depth > result[1]) {
                result = [x, depth];
            }
            for (const target of edge[x]) {
                if (target !== parent) {
                    queue.push([target, x, depth + 1]);
                }
            }
        }

        return result;
    };

    const [v1] = bfs(1);
    const [v2, d] = bfs(v1);

    if (d & 1) {
        console.log(-1);
        return;
    }

    let mid = v2;
    for (let i = d; i !== d/2; i--, mid = p[mid]) {}

    const check = (initX) => {
        const degrees = {};
        const queue = [[initX, -1, 0]];
        let top = 0;
        while (top < queue.length) {
            const [x, parent, depth] = queue[top];
            if (degrees[depth] === undefined) {
                degrees[depth] = edge[x].length;
            } else if (edge[x].length !== degrees[depth]) {
                return false;
            }
            top += 1;
            for (const target of edge[x]) {
                if (target !== parent) {
                    queue.push([target, x, depth + 1]);
                }
            }
        }

        return true;
    };

    if (check(mid)) {
        console.log(mid);
        return;
    }
    // leaf
    for (let i = 1; i <= n; i++) {
        if (edge[i].length === 1) {
            if (check(i)) {
                console.log(i);
                return;
            } else {
                const [j] = bfs(i);
                if (check(j)) {
                    console.log(j);
                    return;
                }
            }
            break;
        }
    }

    console.log(-1);
})

const readline = require('readline');
const rl = readline.createInterface(
    {
        input: process.stdin,
    }
);
const lines = [];
rl.on('line', x => lines.push(x));
rl.on('close', () => {
    const n = parseInt(lines[0], 10);
    if (n === 1) {
        console.log(1);
        return;
    }

    const edge = {};
    for (let i = 1; i < n; i++) {
        const [x, y] = lines[i].split(' ').map(a => parseInt(a));
        if (!edge[x]) {
            edge[x] = [];
        }
        edge[x].push(y);
        if (!edge[y]) {
            edge[y] = [];
        }
        edge[y].push(x);
    }

    const p = {};
    const bfs = (initX) => {
        const queue = [[initX, -1, 0]];
        let top = 0;
        let result = [initX, 0];
        while (top < queue.length) {
            const [x, parent, depth] = queue[top];
            p[x] = parent;
            top += 1;
            if (depth > result[1]) {
                result = [x, depth];
            }
            for (const target of edge[x]) {
                if (target !== parent) {
                    queue.push([target, x, depth + 1]);
                }
            }
        }

        return result;
    };

    const [v1] = bfs(1);
    const [v2, d] = bfs(v1);

    if (d & 1) {
        console.log(-1);
        return;
    }

    let mid = v2;
    for (let i = d; i !== d/2; i--, mid = p[mid]) {}

    const check = (initX) => {

        const degrees = {};
        const queue = [[initX, -1, 0]];
        let top = 0;
        while (top < queue.length) {
            const [x, parent, depth] = queue[top];
            if (degrees[depth] === undefined) {
                degrees[depth] = edge[x].length;
            } else if (edge[x].length !== degrees[depth]) {
                return false;
            }
            top += 1;
            for (const target of edge[x]) {
                if (target !== parent) {
                    queue.push([target, x, depth + 1]);
                }
            }
        }

        return true;
    };

    if (check(mid, -1, 0)) {
        console.log(mid);
    } else {
        console.log(-1);
    }
})

const readline = require('readline');
const rl = readline.createInterface(
    {
        input: process.stdin,
    }
);
const lines = [];
rl.on('line', x => lines.push(x));
rl.on('close', () => {
    const n = parseInt(lines[0], 10);
    const nodes = Array.from({length: n}, (_, i) => i + 1);
    if (n === 1) {
        console.log(1);
        return;
    }

    const edge = {};
    for (let i = 1; i < n; i++) {
        const [x, y] = lines[i].split(' ').map(a => parseInt(a));
        if (!edge[x]) {
            edge[x] = [];
        }
        edge[x].push(y);
        if (!edge[y]) {
            edge[y] = [];
        }
        edge[y].push(x);
    }

    let parent;
    let depth;
    const bfs = (initX, initP) => {
        parent = {};
        depth = {};
        parent[initX] = -1;
        depth[initX] = 0;
        if (initP !== undefined) {
            parent[initX] = initP;
        }
        const queue = [initX];
        let top = 0;
        while (top < queue.length) {
            const x = queue[top];
            top += 1;
            for (const target of edge[x]) {
                if (target !== parent[x]) {
                    parent[target] = x;
                    depth[target] = depth[x] + 1;
                    queue.push(target);
                }
            }
        }
    };

    const check = (initX) => {
        bfs(initX);
        const degrees = {};
        for (const x of nodes) {
            const d = depth[x];
            if (degrees[d] === undefined) {
                degrees[d] = edge[x].length;
            } else if (edge[x].length !== degrees[d]) {
                return false;
            }
        }

        return true;
    };

    // find mid
    bfs(1);
    let d = Math.max(...Object.values(depth));
    const v1 = nodes.find(x => depth[x] === d);
    bfs(v1);
    d = Math.max(...Object.values(depth));
    const v2 = nodes.find(x => depth[x] === d);
    if ((d % 2) === 0) {
        // check mid
        let mid = v2;
        for (let i = d; i !== d/2; i--, mid = parent[mid]) {}
        if (check(mid)) {
            console.log(mid);
            return;
        }
        // check leaf2
        const degrees = {};
        const leader = {};
        for (const x of nodes) {
            const d = depth[x];
            if (degrees[d] === undefined) {
                degrees[d] = edge[x].length;
                leader[d] = x;
            } else if (edge[x].length !== degrees[d]) {
                const targets = [leader[d], x];
                const p2 = parent;
                for (const node of targets) {
                    bfs(node, p2[node]);
                    let d = Math.max(...Object.values(depth));
                    const v = nodes.find(x => depth[x] === d);
                    if (check(v)) {
                        console.log(v);
                        return;
                    }
                }
                break;
            }
        }
    }

    // check leaf1
    if (check(v2)) {
        console.log(v2);
        return;
    }

    console.log(-1);
})

const fs = require('fs');
const text = fs.readFileSync(0, 'utf8');
const lines = text.split('\n').map(x => x.trim());
const n = parseInt(lines[0], 10);
if (n === 1) {
    console.log(1);
    return;
}

const edge = {};
for (let i = 1; i <= n; i++) {
    const [x, y] = lines[i].split(' ').map(a => parseInt(a));
    if (!edge[x]) {
        edge[x] = [];
    }
    edge[x].push(y);
    if (!edge[y]) {
        edge[y] = [];
    }
    edge[y].push(x);
}

const p = {};
const bfs = (initX) => {
    const queue = [[initX, -1, 0]];
    let top = 0;
    let result = [initX, 0];
    while (top < queue.length) {
        const [x, parent, depth] = queue[top];
        p[x] = parent;
        top += 1;
        if (depth > result[1]) {
            result = [x, depth];
        }
        for (const target of edge[x]) {
            if (target !== parent) {
                queue.push([target, x, depth + 1]);
            }
        }
    }

    return result;
};

const [v1] = bfs(1);
const [v2, d] = bfs(v1);

if (d & 1) {
    console.log(-1);
    return;
}

let mid = v2;
for (let i = d; i !== d/2; i--, mid = p[mid]) {}

const check = (initX) => {

    const degrees = {};
    const queue = [[initX, -1, 0]];
    let top = 0;
    while (top < queue.length) {
        const [x, parent, depth] = queue[top];
        if (degrees[depth] === undefined) {
            degrees[depth] = edge[x].length;
        } else if (edge[x].length !== degrees[depth]) {
            return false;
        }
        top += 1;
        for (const target of edge[x]) {
            if (target !== parent) {
                queue.push([target, x, depth + 1]);
            }
        }
    }

    return true;
};

if (check(mid, -1, 0)) {
    console.log(mid);
} else {
    console.log(-1);
}


This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le q \le 3 \cdot 10^5$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.

NoteLet's look at the third test case:Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5-3+7=9$$$.After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be $$$2-1+5-3+7=10$$$.After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be $$$2-1+5-3+7=10$$$.After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be $$$2-1+5-3+7=10$$$.After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be $$$5-3+7=9$$$.After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be $$$4-2+5-3+7=11$$$.

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, fn, init) {
  if (a < b) {
    let arr = Array(b + 1);
    if (init) init(arr);
    for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
    return arr;
  } else {
    let arr = Array(a + 1);
    if (init) init(arr);
    for (let i = a; i >= b; i--) 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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  let test = inp[r++];
  // let ans = [];
  while (test--) {
    let n = inp[r++], q = inp[r++];
    // let a = Arr(1, n, (i, a) => a[i] = inp[r++], a => a[0] = a[n + 1] = 0)
    // let cal = i => {
    //   if (a[i] > a[i - 1] && a[i] > a[i + 1]) return a[i]
    //   if (a[i] < a[i - 1] && a[i] < a[i + 1]) return -a[i];
    //   return 0;
    // }
    // let b = Arr(1, n, (i, b) => b[i] = cal(i), b => b[0] = b[n + 1] = 0);
    // let res = b.sum();
    // console.log(res);
    // let update = (i, v) => {
    //   res -= b[i - 1] + b[i] + b[i + 1];
    //   a[i] = v;
    //   b[i] = cal(i);
    //   if (i > 1) b[i - 1] = cal(i - 1)
    //   if (i < n) b[i + 1] = cal(i + 1)
    //   res += b[i - 1] + b[i] + b[i + 1];
    // }
    // if (q) For(1, q, i => {
    //   let li = inp[r++], ri = inp[r++];
    //   let temp = a[li];
    //   update(li, a[ri]);
    //   update(ri, temp);
    //   console.log(res);
    // })

    let a = Array(n + 2).fill(0);
    for (let i = 1; i <= n; i++) a[i] = inp[r++];
    let b = Array(n + 2).fill(0);
    let cal = i => {
      if (a[i] > a[i - 1] && a[i] > a[i + 1]) b[i] = a[i];
      else if (a[i] < a[i - 1] && a[i] < a[i + 1]) b[i] = -a[i];
      else b[i] = 0;
    }
    for (let i = 1; i <= n; i++) cal(i);
    let res = 0;
    for (let i = 1; i <= n; i++) res += b[i];
    // ans.push(res);
    process.stdout.write(res + '\n');
    let update = (i, v) => {
      res -= b[i - 1] + b[i] + b[i + 1];
      a[i] = v;
      cal(i);
      if (i > 1) cal(i - 1);
      if (i < n) cal(i + 1);
      res += b[i - 1] + b[i] + b[i + 1];
    }
    while (q--) {
      let li = inp[r++], ri = inp[r++];
      let temp = a[li];
      update(li, a[ri]);
      update(ri, temp);
      process.stdout.write(res + '\n');
    }
  }
  // console.log(ans.join('\n'))
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, step, fn, init) {
  let arr = Array(Math.max(a, b) + 1);
  if (init) init(arr);
  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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v), _r = 0, $ = n => n != null ? inp.slice(_r, _r += n) : inp[_r++], out = [];
  let test = $()
  while (test--) {
    let [n, q] = $(2)
    let a = Arr(1, n, 1, (i, a) => a[i] = $(), a => a[0] = a[n + 1] = 0)
    let cal = i => {
      if (a[i] > a[i - 1] && a[i] > a[i + 1]) return a[i]
      if (a[i] < a[i - 1] && a[i] < a[i + 1]) return -a[i];
      return 0;
    }
    let b = Arr(1, n, 1, (i, b) => b[i] = cal(i), b => b[0] = b[n + 1] = 0);
    let res = b.sum();
    out.push(res);
    let update = (i, v) => {
      res -= b[i - 1] + b[i] + b[i + 1];
      a[i] = v;
      b[i] = cal(i);
      if (i > 1) b[i - 1] = cal(i - 1)
      if (i < n) b[i + 1] = cal(i + 1)
      res += b[i - 1] + b[i] + b[i + 1];
    }
    while (q--) {
      let [li, ri] = $(2)
      let temp = a[li];
      update(li, a[ri]);
      update(ri, temp);
      out.push(res);
    }
  }
  console.log(out.join('\n'))
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, step, fn, init) {
  let arr = Array(Math.max(a, b) + 1);
  if (init) init(arr);
  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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  let test = inp[r++];
  let ans = [];
  while (test--) {
    let n = inp[r++], q = inp[r++];
    let a = Arr(1, n, 1, (i, a) => a[i] = inp[r++], a => a[0] = a[n + 1] = 0)
    let cal = i => {
      if (a[i] > a[i - 1] && a[i] > a[i + 1]) return a[i]
      if (a[i] < a[i - 1] && a[i] < a[i + 1]) return -a[i];
      return 0;
    }
    let b = Arr(1, n, 1, (i, b) => b[i] = cal(i), b => b[0] = b[n + 1] = 0);
    let res = b.sum();
    ans.push(res);
    let update = (i, v) => {
      res -= b[i - 1] + b[i] + b[i + 1];
      a[i] = v;
      b[i] = cal(i);
      if (i > 1) b[i - 1] = cal(i - 1)
      if (i < n) b[i + 1] = cal(i + 1)
      res += b[i - 1] + b[i] + b[i + 1];
    }
    For(1, q, 1, i => {
      let li = inp[r++], ri = inp[r++];
      let temp = a[li];
      update(li, a[ri]);
      update(ri, temp);
      ans.push(res);
    })
  }
  console.log(ans.join('\n'))
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, fn, init) {
  if (a < b) {
    let arr = Array(b + 1);
    if (init) init(arr);
    for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
    return arr;
  } else {
    let arr = Array(a + 1);
    if (init) init(arr);
    for (let i = a; i >= b; i--) 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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  let test = inp[r++];
  let ans = [];
  while (test--) {
    let n = inp[r++], q = inp[r++];
    // let a = Arr(1, n, (i, a) => a[i] = inp[r++], a => a[0] = a[n + 1] = 0)
    // let cal = i => {
    //   if (a[i] > a[i - 1] && a[i] > a[i + 1]) return a[i]
    //   if (a[i] < a[i - 1] && a[i] < a[i + 1]) return -a[i];
    //   return 0;
    // }
    // let b = Arr(1, n, (i, b) => b[i] = cal(i), b => b[0] = b[n + 1] = 0);
    // let res = b.sum();
    // console.log(res);
    // let update = (i, v) => {
    //   res -= b[i - 1] + b[i] + b[i + 1];
    //   a[i] = v;
    //   b[i] = cal(i);
    //   if (i > 1) b[i - 1] = cal(i - 1)
    //   if (i < n) b[i + 1] = cal(i + 1)
    //   res += b[i - 1] + b[i] + b[i + 1];
    // }
    // if (q) For(1, q, i => {
    //   let li = inp[r++], ri = inp[r++];
    //   let temp = a[li];
    //   update(li, a[ri]);
    //   update(ri, temp);
    //   console.log(res);
    // })

    let a = Array(n + 2).fill(0);
    for (let i = 1; i <= n; i++) a[i] = inp[r++];
    let b = Array(n + 2).fill(0);
    let cal = i => {
      if (a[i] > a[i - 1] && a[i] > a[i + 1]) b[i] = a[i];
      else if (a[i] < a[i - 1] && a[i] < a[i + 1]) b[i] = -a[i];
      else b[i] = 0;
    }
    for (let i = 1; i <= n; i++) cal(i);
    let res = 0;
    for (let i = 1; i <= n; i++) res += b[i];
    ans.push(res);
    let update = (i, v) => {
      res -= b[i - 1] + b[i] + b[i + 1];
      a[i] = v;
      cal(i);
      if (i > 1) cal(i - 1);
      if (i < n) cal(i + 1);
      res += b[i - 1] + b[i] + b[i + 1];
    }
    while (q--) {
      let li = inp[r++], ri = inp[r++];
      let temp = a[li];
      update(li, a[ri]);
      update(ri, temp);
      ans.push(res);
    }
  }
  console.log(ans.join('\n'))
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, fn, init) {
  if (a < b) {
    let arr = Array(b + 1).fill(0);
    if (init) init(arr);
    for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
    return arr;
  } else {
    let arr = Array(a + 1).fill(0);
    if (init) init(arr);
    for (let i = a; i >= b; i--) 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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  let test = inp[r++];
  while (test--) {
    let n = inp[r++], q = inp[r++];
    let a = Arr(1, n, (i, a) => a[i] = inp[r++], a => a[0] = a[n + 1] = 0)
    let cal = i => (a[i] > a[i - 1] && a[i] > a[i + 1]) ? 1 : (a[i] < a[i - 1] && a[i] < a[i + 1]) ? -1 : 0;
    let b = Arr(1, n, (i, b) => b[i] = cal(i), b => b[0] = b[n + 1] = 0);
    let res = 0;
    For(1, n, i => { res += a[i] * b[i] });
    console.log(res);
    let update = (i, v) => {
      res -= a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
      a[i] = v;
      b[i] = cal(i);
      if (i > 1) b[i - 1] = cal(i - 1)
      if (i < n) b[i + 1] = cal(i + 1)
      res += a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
    }
    For(1, q, i => {
      let li = inp[r++], ri = inp[r++];
      let temp = a[li];
      update(li, a[ri]);
      update(ri, temp);
      console.log(res);
    })

    // let a = Array(n + 2).fill(0);
    // for (let i = 1; i <= n; i++) a[i] = inp[r++];
    // let b = Array(n + 2).fill(0);
    // let cal = i => {
    //   if (a[i] > a[i - 1] && a[i] > a[i + 1]) return 1;
    //   if (a[i] < a[i - 1] && a[i] < a[i + 1]) return -1;
    //   return 0;
    // }
    // for (let i = 1; i <= n; i++) b[i] = cal(i);
    // let res = 0;
    // for (let i = 1; i <= n; i++) res += a[i] * b[i];
    // console.log(res);
    // let update = (i, v) => {
    //   res -= a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
    //   a[i] = v;
    //   b[i] = cal(i);
    //   if (i > 1) b[i - 1] = cal(i - 1);
    //   if (i < n) b[i + 1] = cal(i + 1);
    //   res -= a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
    // }
    // while (q--) {
    //   let li = inp[r++], ri = inp[r++];
    //   let temp = a[li];
    //   update(li, a[ri]);
    //   update(ri, temp);
    //   console.log(res);
    // }
  }
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, fn, init) {
  if (a < b) {
    let arr = Array(b + 1);
    if (init) init(arr);
    for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
    return arr;
  } else {
    let arr = Array(a + 1);
    if (init) init(arr);
    for (let i = a; i >= b; i--) 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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  let test = inp[r++];
  while (test--) {
    let n = inp[r++], q = inp[r++];
    let a = Arr(1, n, (i, a) => a[i] = inp[r++], a => a[0] = a[n + 1] = 0)
    let cal = i => a[i] > a[i - 1] && a[i] > a[i + 1] ? 1 : a[i] < a[i - 1] && a[i] < a[i + 1] ? -1 : 0;
    let b = Arr(1, n, (i, b) => b[i] = cal(i), b => b[0] = b[n + 1] = 0);
    let res = 0;
    For(1, n, i => { res += a[i] * b[i] });
    console.log(res);
    let update = (i, v) => {
      res -= a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
      a[i] = v;
      b[i] = cal(i);
      if (i >= 2) b[i - 1] = cal(i - 1)
      if (i <= n - 1) b[i + 1] = cal(i + 1)
      res += a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
    }
    For(1, q, i => {
      let li = inp[r++], ri = inp[r++];
      let temp = a[li];
      update(li, a[ri]);
      update(ri, temp);
      console.log(res);
    })
  }
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

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

function Arr(a, b, fn, init) {
  if (a < b) {
    let arr = Array(b + 1);
    if (init) init(arr);
    for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
    return arr;
  } else {
    let arr = Array(a + 1);
    if (init) init(arr);
    for (let i = a; i >= b; i--) 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

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  let test = inp[r++];
  while (test--) {
    let n = inp[r++], q = inp[r++];
    let a = Arr(1, n, (i, a) => a[i] = inp[r++], a => a[0] = a[n + 1] = 0)
    let b = Arr(1, n, (i, b) => b[i] = a[i] > a[i - 1] && a[i] > a[i + 1] ? 1 : a[i] < a[i - 1] && a[i] < a[i + 1] ? -1 : 0, b => b[0] = b[n + 1] = 0);
    let res = 0;
    For(1, n, i => { res += a[i] * b[i] });
    console.log(res);
    let update = (i, v) => {
      res -= a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
      a[i] = v;
      b[i] = a[i] > a[i - 1] && a[i] > a[i + 1] ? 1 : a[i] < a[i - 1] && a[i] < a[i + 1] ? -1 : 0
      if (i >= 2) b[i - 1] = a[i - 1] > a[i - 2] && a[i - 1] > a[i] ? 1 : a[i - 1] < a[i - 2] && a[i - 1] < a[i] ? -1 : 0
      if (i <= n - 1) b[i + 1] = a[i + 1] > a[i] && a[i + 1] > a[i + 2] ? 1 : a[i + 1] < a[i] && a[i + 1] < a[i + 2] ? -1 : 0
      res += a[i - 1] * b[i - 1] + a[i] * b[i] + a[i + 1] * b[i + 1];
    }
    For(1, q, i => {
      let li = inp[r++], ri = inp[r++];
      let temp = a[li];
      update(li,a[ri]);
      update(ri,temp);
      console.log(res);
    })
  }
})();


The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.

The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second.

Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.  Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if  holds.

NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.

var n=+readline()
var x=readline().split(' ').map(function(q){return +q})
var v=readline().split(' ').map(function(q){return +q})

function max(a,b)
{
    if (a>b){return a;}
    else{return b;}
}

function res(a)
{
    v1=Math.abs(x[0]-a)/v[0]
    for (var i=1;i<n;i++)
    {
        v1=max(v1,Math.abs(x[i]-a)/v[i])
    }
    return v1
}

var l=0
var r=1000000000
for (var i=0;i<=1000;i++)
{
    var m1=(l+l+r)/3;
    var m2=(l+r+r)/3;
    var h1=res(m1)
    var h2=res(m2)
    if (h1>h2)
    {
        l=m1
    }
    else
    {
        r=m2
    }
}

print(res(l))

var n = parseInt(readline());
var minx = Infinity;
var maxx = -1;
var x = readline().split(' ').map(function(x) {
  var n = parseInt(x);
  minx = minx > n ? n : minx;
  maxx = maxx < n ? n : maxx;
  return n;
});
var v = readline().split(' ').map(function(x) {
  return parseInt(x);
});

var calc = function(d) {
  var res = -1;
  for(var i = 0; i < x.length; i += 1) {
    var tmp = Math.abs(x[i] - d) / v[i];
    res = res < tmp ? tmp : res;
  }
  return res;
};

for(var k = 0; k < 64; k += 1) {
  var l = minx + (maxx - minx) / 3;
  var r = minx + (maxx - minx) / 3 * 2;
  if(calc(l) < calc(r)) {
    maxx = r;
  } else {
    minx = l;
  }
}

print(calc(minx));


Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.Of course, biathlon as any sport, proved very difficult in practice. It takes much time and effort. Workouts, workouts, and workouts, — that's what awaited Valera on his way to great achievements in biathlon.As for the workouts, you all probably know that every professional biathlete should ski fast and shoot precisely at the shooting range. Only in this case you can hope to be successful, because running and shooting are the two main components of biathlon. Valera has been diligent in his ski trainings, which is why he runs really fast, however, his shooting accuracy is nothing to write home about.On a biathlon base where Valera is preparing for the competition, there is a huge rifle range with n targets. Each target have shape of a circle, and the center of each circle is located on the Ox axis. At the last training session Valera made the total of m shots. To make monitoring of his own results easier for him, one rather well-known programmer (of course it is you) was commissioned to write a program that would reveal how many and which targets Valera hit. More specifically, for each target the program must print the number of the first successful shot (in the target), or "-1" if this was not hit. The target is considered hit if the shot is inside the circle or on its boundary. Valera is counting on you and perhaps, thanks to you he will one day win international competitions.

The first line of the input file contains the integer n (1 ≤ n ≤ 104), which is the number of targets. The next n lines contain descriptions of the targets. Each target is a circle whose center is located on the Ox axis. Each circle is given by its coordinate of the center x ( - 2·104 ≤ x ≤ 2·104) and its radius r (1 ≤ r ≤ 1000). It is guaranteed that no two targets coincide, intersect or are nested into each other, but they can touch each other.  The next line contains integer m (1 ≤ m ≤ 2·105), which is the number of shots. Next m lines contain descriptions of the shots, which are points on the plane, given by their coordinates x and y ( - 2·104 ≤ x, y ≤ 2·104). All the numbers in the input are integers.  Targets and shots are numbered starting from one in the order of the input.

Print on the first line a single number, the number of targets hit by Valera. Print on the second line for each of the targets the number of its first hit or "-1" (without quotes) if this number does not exist. Separate numbers with spaces.

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let SHIFT = 21000
  const ils = ipt.split(EOL).slice(0, -1)
  let n = +ils[0]
  let M = ils.slice(1, n + 1).map((line, i) => {
    line = line.split(' ').map(v => parseInt(v))
    return [i + 1, line[0] + SHIFT, line[1]]
  })
  let V = ils.slice(n + 2).map(line => {
    line = line.split(' ').map(v => parseInt(v))
    return [line[0] + SHIFT, line[1]]
  })
  let Mx = []
  for (let i = 0; i < M.length; i++) {
    let x = M[i][1]
    let r = M[i][2]
    for (let j = x - r; j <= x + r; j++) {
      if (Mx[j]) {
        Mx[j] = Mx[j].concat(M[i])
      } else {
        Mx[j] = M[i]
      }
    }
  }

  let H = []

  for (let v = 1; v <= V.length; v++) {
    let xv = V[v - 1][0]
    let yv = V[v - 1][1]
    if (Mx[xv]) {
      let nm = Mx[xv][0]
      if (yv == 0) {
        H[nm] = H[nm] || v
        if (Mx[xv].length == 6) {
          let nvm = Mx[xv][3]
          H[nvm] = H[nvm] || v
        }
      } else {
        let xm = Mx[xv][1]
        let rm = Mx[xv][2]
        if (Math.pow(xm - xv, 2) + yv * yv <= rm * rm) {
          H[nm] = H[nm] || v
        }
      }
    }
  }

  let c = 0
  for (let i = 0; i < M.length; i++) {
    if (H[i + 1]) c++
    else H[i + 1] = -1
  }

  console.log(c)
  console.log(H.slice(1).join(' '))
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let SHIFT = 21000
  const ils = ipt.split(EOL).slice(0, -1)
  let n = +ils[0]
  let M = ils.slice(1, n + 1).map((line, i) => {
    line = line.split(' ').map(v => parseInt(v))
    return [i + 1, line[0] + SHIFT, line[1] * line[1]]
  })
  let V = ils.slice(n + 2).map(line => {
    line = line.split(' ').map(v => parseInt(v))
    return [line[0] + SHIFT, line[1]]
  })
  let Mx = []
  for (let i = 0; i < M.length; i++) {
    let x = M[i][1]
    let r = M[i][2]
    for (let j = x - r; j <= x + r; j++) {
      if (Mx[j]) {
        Mx[j] = Mx[j].concat(M[i])
      } else {
        Mx[j] = M[i]
      }
    }
  }

  let H = []

  for (let v = 1; v <= V.length; v++) {
    let xv = V[v - 1][0]
    let yv = V[v - 1][1]
    if (Mx[xv]) {
      let nm = Mx[xv][0]
      if (yv == 0) {
        H[nm] = H[nm] || v
        if (Mx[xv].length == 6) {
          let nvm = Mx[xv][3]
          H[nvm] = H[nvm] || v
        }
      } else {
        let xm = Mx[xv][1]
        let rm = Mx[xv][2]
        if (Math.pow(xm - xv, 2) + yv * yv <= rm * rm) {
          H[nm] = H[nm] || v
        }
      }
    }
  }

  let c = 0
  for (let i = 0; i < M.length; i++) {
    if (H[i + 1]) c++
    else H[i + 1] = -1
  }

  console.log(c)
  console.log(H.slice(1).join(' '))
})


You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, so pk = qk for 1 ≤ k < i and pi < qi.

The first line contains two integers n and m (1 ≤ n, m ≤ 106) — the length of the permutation p and the number of pairs of positions. The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p. Each of the last m lines contains two integers (aj, bj) (1 ≤ aj, bj ≤ n) — the pairs of positions to swap. Note that you are given a positions, not the values to swap.

Print the only line with n distinct integers p'i (1 ≤ p'i ≤ n) — the lexicographically maximal permutation one can get.

var uf = new Int32Array(1000000);
uf.fill(-1);

function find(a)
{
  var stack = [];
  while (uf[a] >= 0)
  {
    stack.push(a);
    a = uf[a];
  }
  for (var i=0 ; i<stack.length ; i++)
  {
    uf[stack[i]] = a;
  }
  return a;
}
function merge(a, b)
{
  a = find(a);
  b = find(b);

  if (a != b)
  {
    if (uf[a] < uf[b])
    {
      uf[b] = a;
    }
    else if (uf[a] > uf[b])
    {
      uf[a] = b;
    }
    else
    {
      uf[a]--;
      uf[b] = a;
    }
  }
}

(function(){
  function mapInt(x) { return parseInt(x, 10); }

  var nm = readline().split(" ").map(mapInt);
  var perm = new Int32Array(readline().split(" ").map(mapInt));

  var n = nm[0];
  var m = nm[1];

  for (var i=0 ; i<m ; i++)
  {
    var ab = readline().split(" ").map(mapInt);
    merge(ab[0]-1, ab[1]-1);
  }

  var map = new Map();
  for (var i=0 ; i<n ; i++)
  {
    var root = find(i);
    if (!map.has(root)) map.set(root, []);

    map.get(root).push(i);
  }

  var out = new Int32Array(n);
  for (var itr=map.values(), o=itr.next() ; !o.done ; o=itr.next())
  {
    var p = o.value;
    var v = new Int32Array(p);
    for (var i=0 ; i<v.length ; i++)
    {
      v[i] = perm[v[i]];
    }
    v.sort(function(a,b)
    {
      return b - a;
    });

    for (var i=0 ; i<v.length ; i++)
    {
      out[p[i]] = v[i];
    }
  }

  print(out.join(" "));
})();


Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute — at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \not\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \le L, v \le 10^9$$$, $$$1 \le l \le r \le L$$$) — destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.

Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer — the answer for the $$$i$$$-th query.

NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path.

var t = Number(readline());

for (var i = 0; i<t ; ++i){
    var arr = readline().split(" ");
    var L = arr[0], u = arr[1], l = arr[2], r =arr[3];
    print(Math.floor(L/u) - Math.floor(r/u)+ Math.floor((l-1)/u));
}

var n = parseInt(readline())

while(n--) {
    input = readline().split(" ").map(e => parseInt(e))
    m = Math.floor(input[0]/input[1])
    d1 = Math.floor(input[2]/input[1])
    d2 = Math.floor(input[3]/input[1])
    input[2]%input[1] === 0? print(m-d2+d1-1): print(m-d2+d1)
}

var N = +readline();
var f = function(x) {
    return +x;
};

for (var i = 0; i < N; ++i) {
    var line = readline().split(' ').map(f);
    var seen = Math.floor(line[0]/line[1]);
    var hidden = Math.floor(line[3]/line[1]) - Math.floor((line[2]-1)/line[1]);
    print(seen-hidden);
}

var t = +readline();
for (var i=0; i<t; i++){
	var s = readline().split(' ').map(Number);
	var Ld = s[0];
	var v = s[1];
	var l = s[2];
	var r = s[3];
	var ans = Math.floor((l-1)/v) + Math.floor((Ld - Math.ceil((r+1)/v)*v)/v) + 1;
	print (ans);
}

var t = Number(readline());

for (var i = 0; i<t ; ++i){
    var arr = readline().split(" ");
    var L = arr[0], u = arr[1], l = arr[2], r =arr[3];
    print(parseInt(L/u) - parseInt(r/u)+ parseInt((l-1)/u));
}

var N = +readline()

for (var i = 0; i < N; ++i) {
    var line = readline().split(' ').map(parseInt);
    var hidden = Math.floor(((line[3] - line[2])/line[1]));
    if(line[3]%line[2] === 0) {
        hidden++
    }
    if(line[4]%line[2] === 0) {
        hidden++
    }

    print(Math.floor((line[0]/line[1]) - hidden));
}

var N = +readline()
var f = function(x) {
    return +x;
}

for (var i = 0; i < N; ++i) {
    var line = readline().split(' ').map(f);
    var hidden = Math.floor(((line[3] - line[2])/line[1]));
    if(line[3]%line[2] === 0) {
        hidden++
    }
    if(line[4]%line[2] === 0) {
        hidden++
    }

    print(Math.floor((line[0]/line[1]) - hidden));
}

var N = +readline();
var f = function(x) {
    return +x;
};

for (var i = 0; i < N; ++i) {
    var line = readline().split(' ').map(f);
    var seen = Math.floor(line[0]/line[1]);
    var hidden = Math.floor(((line[3] - line[2])/line[1]));
    if(line[2]%line[1] === 0 || line[3]%line[1] === 0) {
        hidden++;
    }

    print(Math.floor(seen - hidden));
}


Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $$$100^{500}$$$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $$$i$$$-th attack is performed at the beginning of the $$$a_i$$$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $$$1$$$ damage during each of the next $$$k$$$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose $$$k = 4$$$, and Monocarp stabs the dragon during the seconds $$$2$$$, $$$4$$$ and $$$10$$$. Then the poison effect is applied at the start of the $$$2$$$-nd second and deals $$$1$$$ damage during the $$$2$$$-nd and $$$3$$$-rd seconds; then, at the beginning of the $$$4$$$-th second, the poison effect is reapplied, so it deals exactly $$$1$$$ damage during the seconds $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$; then, during the $$$10$$$-th second, the poison effect is applied again, and it deals $$$1$$$ damage during the seconds $$$10$$$, $$$11$$$, $$$12$$$ and $$$13$$$. In total, the dragon receives $$$10$$$ damage.Monocarp knows that the dragon has $$$h$$$ hit points, and if he deals at least $$$h$$$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $$$k$$$ (the number of seconds the poison effect lasts) that is enough to deal at least $$$h$$$ damage to the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 100; 1 \le h \le 10^{18}$$$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9; a_i < a_{i + 1}$$$), where $$$a_i$$$ is the second when the $$$i$$$-th attack is performed.

For each test case, print a single integer — the minimum value of the parameter $$$k$$$, such that Monocarp will cause at least $$$h$$$ damage to the dragon.

NoteIn the first example, for $$$k=3$$$, damage is dealt in seconds $$$[1, 2, 3, 5, 6, 7]$$$.In the second example, for $$$k=4$$$, damage is dealt in seconds $$$[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$$$.In the third example, for $$$k=1$$$, damage is dealt in seconds $$$[1, 2, 4, 5, 7]$$$.

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));
const rnba = () => ra().map(x => BigInt(x));

function can (a, h, k) {
	for (let i = 0; i < a.length - 1; i++) {
		if (k < BigInt(a[i+1] - a[i]))
			h -= k;
		else
			h -= BigInt(a[i+1] - a[i]);
	}
	h -= k;
	return h <= 0;
}

function main () {
	let T = rn();
	while (T--) {
		let [n, h] = rnba();
		n = Number(n);
		let a = rna();

		let l = 0n, r = BigInt(1e18);
		while (l < r) {
			const mid = (l+r)/2n;
			if (can(a, h, mid)) {
				r = mid;
			} else {
				l = mid + 1n;
			}
		}
		const ans = l;

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

data = '';

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

  let [_, ...input]= data
      .trim()
      .split(/\n/)
      .map(el => el.trim())

input = input
      .map(el => el.split(' '))
      const output = [];

    for (let i = 0; i < input.length; i += 2) {
    const n = BigInt(input[i][0].trim());
    const h = BigInt(input[i][1].trim());
      const arr = input[i+1].map(el => BigInt(el.trim()));

      let left = 0n;
    let right = h;

    while (left <= right) {
      let mid = ~~((left + right) / 2n);
      if (calculate_damage(arr, n, mid) >= h) {
        right = mid - 1n;
      } else {
        left = mid + 1n;
      }
    }

    output[i] = left;

    };
    console.log(output.join('\n'))

function calculate_damage(gagarini, n, k) {
  let total_damage = 0n;

  for (let i = 1; i < n; i++) {
    if(BigInt(gagarini[i] - gagarini[i - 1]) < k){
      total_damage += BigInt(gagarini[i] - gagarini[i - 1])
    }else{
      total_damage += k;
    }
    //total_damage += Math.min(BigInt(gagarini[i] - gagarini[i - 1]), k);
  }

  total_damage += k;

  return total_damage;
}

})

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

function solve(n, h, arr) {
    const cal = x => {
        let sum = 0n
        let prev = 0n
        arr.forEach(t => {
            const start = prev < t ? t : prev
            const last = t + x - 1n
            if (last >= start) sum += last - start + 1n
            prev = last + 1n
        })
        // console.log(x, sum)
        return sum
    }
    const k = binarySearch(1n, h, x => cal(x) <= h)
    return cal(k) < h ? k + 1n : k
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        // const m = Math.floor((l + r) / 2)
        const m = (l + r) / 2n
        if (fn(m)) {
            l = m + 1n
        } else {
            r = m - 1n
        }
    }
    return r
}

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

const INF = 1e18+1;

function main () {
	let T = rn();
	while (T--) {
		let [n, h] = rna();
		let a = rna();

		let d = new Map();
		d.set(INF, 1);
		for (let i = 1; i < n; i++) {
			const df = a[i] - a[i-1];
			d.set(df, d.has(df) ? d.get(df) + 1 : 1);
		}
		d = new Map([...d.entries()].sort((a, b) => a[0] - b[0]));

		let ans = 0 ;
		const itr = d.entries();
		while (h > 0) {
			const [df, cnt] = itr.next().value;

			const needs = Math.ceil(h / n);
			const dflft = df - ans;
			const using = Math.min(dflft, needs);
			h -= using*n;
			n -= cnt;
			ans += using;
		}

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

const INF = 1e18+1;

function main () {
	let T = rn();
	while (T--) {
		let [n, h] = rna();
		let a = rna();

		let d = new Map();
		d.set(INF, 1);
		for (let i = 1; i < n; i++) {
			const df = a[i] - a[i-1];
			d.set(df, d.has(df) ? d.get(df) + 1 : 1);
		}
		d = new Map([...d.entries()].sort((a, b) => a[0] - b[0]));

		let ans = 0 ;
		const itr = d.entries();
		while (n) {
			let [df, cnt] = itr.next().value;
			const needs = Math.ceil(h / n);
			df -= ans;
			if (df >= needs) {
				ans += needs;
				n = 0;
			} else {
				ans += df;
				h -= df*n;
				n -= cnt;
			}
		}

		console.log(ans);
	}
}