A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to at most one vertex.The gardener Vitaly grew a tree from $$$n$$$ vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes all leaves of the tree.  Example of a tree. For example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree.  The result of applying the operation "remove all leaves" to the tree. Note the special cases of the operation:  applying an operation to an empty tree (of $$$0$$$ vertices) does not change it;  applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf);  applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves). Vitaly applied $$$k$$$ operations sequentially to the tree. How many vertices remain?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. Each test case consists of several lines. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 4 \cdot 10^5$$$, $$$1 \le k \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of operations, respectively. Then $$$n - 1$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges. It is guaranteed that the sum of $$$n$$$ from all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output on a separate line a single integer — the number of vertices that remain in the tree after applying $$$k$$$ operations.

NoteThe first test case is considered in the statement.The second test case contains a tree of two vertices. $$$200000$$$ operations are applied to it. The first one removes all two vertices, the other operations do not change the tree.In the third test case, a tree of three vertices is given. As a result of the first operation, only $$$1$$$ vertex remains in it (with the index $$$2$$$), the second operation makes the tree empty.

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

function solve(n, k, edges) {
    if (n === 1) return 0
    // console.log(edges)
    const adj = {}
    const d = []
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
        d[a] = (d[a] || 0) + 1
        d[b] = (d[b] || 0) + 1
    })

    let q = []
    for (let u = 1; u <= n; u++) {
        if (d[u] === 1) q.push(u)
    }
// console.log(d)
    let ans = n
    const visited = {}
    for (let i = 0; i < k; i++) {
        const next = []
        for (let j = 0; j < q.length; j++) {
            const u = q[j]
            if (visited[u]) continue
            visited[u] = 1
            ans--

            (adj[u] || []).forEach(v => {
                if (!visited[v] && --d[v] === 1) {
                    next.push(v)
                }
            })
        }
        q = next
        if (!q.length) break
    }
    return ans
}

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
    //  console.log(...args);
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INF = Number.MAX_SAFE_INTEGER;
const INIT = -1;
let n;
let k;
let adjList;
let ld;
function diam() {
    let dist = af(n + 1).fill(INIT);
    dist[1] = 0;
    let q = [1];
    for (let i = 0; i < q.length; i++) {
        let u = q[i];
        for (let v of adjList[u]) {
            if (dist[v] == INIT) {
                dist[v] = dist[u] + 1;
                q.push(v);
            }
        }
    }
    let s = INIT;
    let mx = INIT;
    for (let u = 1; u <= n; u++) {
        if (mx < dist[u]) {
            mx = dist[u];
            s = u;
        }
    }
    check(s != INIT);
    const p = af(n + 1).fill(INIT);
    dist.fill(INIT);
    dist[s] = 0;
    q = [s];
    for (let i = 0; i < q.length; i++) {
        let u = q[i];
        for (let v of adjList[u]) {
            if (dist[v] == INIT) {
                dist[v] = dist[u] + 1;
                p[v] = u;
                q.push(v);
            }
        }
    }
    let t = INIT;
    mx = INIT;
    for (let u = 1; u <= n; u++) {
        if (mx < dist[u]) {
            mx = dist[u];
            t = u;
        }
    }
    check(t != INIT);
    const rv = [t];
    for (let i = 0; i < mx; i++) {
        rv.push(p[t]);
        t = p[t];
    }
    return rv;
}
function getLd(s, ex) {
    const dist = af(n + 1).fill(INIT);
    const p = af(n + 1).fill(INIT);
    if (ex != INIT) {
        dist[ex] = 0;
    }
    dist[s] = 0;
    const q = [s];
    const topo = [];
    for (let i = 0; i < q.length; i++) {
        let u = q[i];
        for (let v of adjList[u]) {
            if (dist[v] == INIT) {
                dist[v] = dist[u] + 1;
                p[v] = u;
                q.push(v);
            }
        }
        topo.push(u);
    }
    for (let i = topo.length - 1; i > 0; i--) {
        let u = topo[i];
        ld[p[u]] = Math.max(ld[p[u]], ld[u] + 1);
    }
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        k = nextInt();
        adjList = Array.from({ length: n + 1 });
        for (let i = 0; i <= n; i++) {
            adjList[i] = [];
        }
        for (let i = 0; i + 1 < n; i++) {
            let u = nextInt();
            let v = nextInt();
            adjList[u].push(v);
            adjList[v].push(u);
        }
        // for (let u = 1; u <= n; u++) {
        //   for (let v of adjList[u]) {
        //     if (u > v) continue;
        //     console.log('u %d v %d', u, v);
        //   }
        // }
        const path = diam();
        let pathlen = path.length;
        ld = af(n + 1).fill(0);
        if ((pathlen % 2) == 0) {
            let r1 = path[Math.trunc(pathlen / 2)];
            let r2 = path[Math.trunc(pathlen / 2) - 1];
            getLd(r1, r2);
            getLd(r2, r1);
        }
        else {
            let root = path[Math.trunc(pathlen / 2)];
            getLd(root, INIT);
        }
        let ans = 0;
        for (let u = 1; u <= n; u++) {
            if (ld[u] >= k) {
                ans++;
            }
        }
        printf("%d\n", ans);
    }
}

'use strict';
const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
//const util = require('util');
//process.stdin.resume();
//process.stdin.setEncoding('ascii');
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
// function printf<T extends readonly unknown[]>(...args: [...T]) {
//   process.stdout.write(util.format(...args));
// //  console.log(...args);
// }
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INF = Number.MAX_SAFE_INTEGER;
const INIT = -1;
let n;
let k;
let adjList;
let ld;
function diam() {
    let dist = af(n + 1).fill(INIT);
    dist[1] = 0;
    let q = [1];
    for (let i = 0; i < q.length; i++) {
        let u = q[i];
        for (let v of adjList[u]) {
            if (dist[v] == INIT) {
                dist[v] = dist[u] + 1;
                q.push(v);
            }
        }
    }
    let s = INIT;
    let mx = INIT;
    for (let u = 1; u <= n; u++) {
        if (mx < dist[u]) {
            mx = dist[u];
            s = u;
        }
    }
    check(s != INIT);
    const p = af(n + 1).fill(INIT);
    dist.fill(INIT);
    dist[s] = 0;
    q = [s];
    for (let i = 0; i < q.length; i++) {
        let u = q[i];
        for (let v of adjList[u]) {
            if (dist[v] == INIT) {
                dist[v] = dist[u] + 1;
                p[v] = u;
                q.push(v);
            }
        }
    }
    let t = INIT;
    mx = INIT;
    for (let u = 1; u <= n; u++) {
        if (mx < dist[u]) {
            mx = dist[u];
            t = u;
        }
    }
    check(t != INIT);
    const rv = [t];
    for (let i = 0; i < mx; i++) {
        rv.push(p[t]);
        t = p[t];
    }
    return rv;
}
function getLd(s, ex) {
    const dist = af(n + 1).fill(INIT);
    const p = af(n + 1).fill(INIT);
    if (ex != INIT) {
        dist[ex] = 0;
    }
    dist[s] = 0;
    const q = [s];
    const topo = [];
    for (let i = 0; i < q.length; i++) {
        let u = q[i];
        for (let v of adjList[u]) {
            if (dist[v] == INIT) {
                dist[v] = dist[u] + 1;
                p[v] = u;
                q.push(v);
            }
        }
        topo.push(u);
    }
    for (let i = topo.length - 1; i > 0; i--) {
        let u = topo[i];
        ld[p[u]] = Math.max(ld[p[u]], ld[u] + 1);
    }
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        k = nextInt();
        adjList = Array.from({ length: n + 1 });
        for (let i = 0; i <= n; i++) {
            adjList[i] = [];
        }
        for (let i = 0; i + 1 < n; i++) {
            let u = nextInt();
            let v = nextInt();
            adjList[u].push(v);
            adjList[v].push(u);
        }
        // for (let u = 1; u <= n; u++) {
        //   for (let v of adjList[u]) {
        //     if (u > v) continue;
        //     console.log('u %d v %d', u, v);
        //   }
        // }
        const path = diam();
        let pathlen = path.length;
        ld = af(n + 1).fill(0);
        if ((pathlen % 2) == 0) {
            let r1 = path[Math.trunc(pathlen / 2)];
            let r2 = path[Math.trunc(pathlen / 2) - 1];
            getLd(r1, r2);
            getLd(r2, r1);
        }
        else {
            let root = path[Math.trunc(pathlen / 2)];
            getLd(root, INIT);
        }
        let ans = 0;
        for (let u = 1; u <= n; u++) {
            if (ld[u] >= k) {
                ans++;
            }
        }
        console.log(ans);
    }
}

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

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

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

let n, k, g, rem, layer;

//q.push(x)
//q.shift() -> remove and return the leftmost element
//q.peek() -> return the leftmost element
//q.size()

class Queue {
	constructor () {
		this.a = [];
		this.p = 0;
	}

	push = (x) => this.a.push(x);
	shift = () => this.size() ? this.a[this.p++] : -1;
	peek = () => this.size() ? this.a[this.p] : -1;
	size  = () => this.a.length - this.p;
}

function main () {
	let T = rn();
	while (T--) {
		rl();
		[n, k] = rna();
		g = Array.from(Array(n), _ => []);
		rem = Array(n).fill(0);
		for (let i = 0; i < n - 1; i++) {
			let [u, v] = rna(); u--, v--;
			g[u].push(v);
			g[v].push(u);
			rem[u]++;
			rem[v]++;
		}
		layer = Array(n).fill(1);

		const q = new Queue();
		for (let i = 0; i < n; i++) if (rem[i] == 1) q.push(i);
		while (q.size()) {
			const u = q.shift();
			for (const v of g[u]) {
				rem[v]--;
				if (rem[v] == 1) {
					layer[v] = layer[u] + 1;
					q.push(v);
				}
			}
		}

		let ans = 0;
		for (let i = 0; i < n; i++) ans += layer[i] > k;
		console.log(ans);
	}
}

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

function solve(n, k, edges) {
    if (n === 1) return 0
    // console.log(edges)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
// return
    let u = 1
    // let p = -1
    // while (1) {
    //     const has = (adj[u] || []).some(v => {
    //         if (v !== p) {
    //             p = u
    //             u = v
    //             return true
    //         }
    //     })
    //     if (!has) break
    // }
    // return
    const [hs, haschild] = dfs(adj, u, {}, k)
// console.log(u, hs, haschild)
    return dfs2(adj, u, {}, k, hs, haschild)
    // let ans = n
    // for (let i = 1; i <= n; i++) {
    //     if (removed[i]) ans--
    // }
    // return ans
}
function dfs(adj, r, visited, k) {
    const stack = [[r, 0, -1]]
    const hs = []
    const haschild = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            hs[u] = 1
            haschild[u] = 0
            ;(adj[u] || []).forEach(v => {
                if (v !== p) {
                    hs[u] = Math.max(hs[u], hs[v] + 1)
                    if (hs[v] >= k) haschild[u]++
                }
            })
            // if (hs[u] <= k) removed[u] = 1
            stack.pop()
        }
    }
    return [hs, haschild]
}
function dfs2(adj, r, visited, k, hs, haschild) {
    const stack = [[r, 0, -1]]
    let count = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            const rh = hs[r] - hs[u] + 1
            if (hs[u] > k && (rh > k || (rh === k && haschild[u] > 1))) {
                // console.log('left', u)
                count++
            }
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return count
}

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

function solve(n, k, edges) {
    if (n === 1) return 0
    // console.log(edges)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
// return
    let u = 1
    // let p = -1
    // while (1) {
    //     const has = (adj[u] || []).some(v => {
    //         if (v !== p) {
    //             p = u
    //             u = v
    //             return true
    //         }
    //     })
    //     if (!has) break
    // }
    // return
    const [hs, haschild] = dfs(adj, u, {}, k)
// console.log(u, hs, haschild)
    return dfs2(adj, u, {}, k, hs, haschild)
    // let ans = n
    // for (let i = 1; i <= n; i++) {
    //     if (removed[i]) ans--
    // }
    // return ans
}
function dfs(adj, r, visited, k) {
    const stack = [[r, 0, -1]]
    const hs = []
    const haschild = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            hs[u] = 1
            haschild[u] = 0
            ;(adj[u] || []).forEach(v => {
                if (v !== p) {
                    hs[u] = Math.max(hs[u], hs[v] + 1)
                    if (hs[v] >= k) haschild[u]++
                }
            })
            // if (hs[u] <= k) removed[u] = 1
            stack.pop()
        }
    }
    return [hs, haschild]
}
function dfs2(adj, r, visited, k, hs, haschild) {
    const stack = [[r, 0, -1]]
    let count = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            const rh = hs[r] - hs[u] + 1
            if (hs[u] > k && (rh > k || (haschild[u] > 1))) {
                // console.log('left', u)
                count++
            }
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return count
}

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

function solve(n, k, edges) {
    if (n === 1) return k < 1 ? 1 : 0
    // console.log(edges)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
// return
    let u = 1
    let p = -1
    while (1) {
        const has = adj[u].some(v => {
            if (v !== p) {
                p = u
                u = v
                return true
            }
        })
        if (!has) break
    }
    // return
    const hs = dfs(adj, u, {})
// console.log(u, hs)
    return dfs2(adj, u, {}, hs, k)
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    const hs = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            hs[u] = 1
            ;(adj[u] || []).forEach(v => {
                if (v !== p) hs[u] = Math.max(hs[u], hs[v] + 1)
            })
            stack.pop()
        }
    }
    return hs
}
function dfs2(adj, r, visited, hs, k) {
    const stack = [[r, 0, -1]]
    let count = 0
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            if (hs[u] > k && hs[r] - hs[u] + 1 > k) {
                count++
            }
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return count
}

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

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

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

let n, k;
let g;
let mp = [];
let ans = 0;

const key = (x, y) => x + ',' + y;

function dfs (u=0, p=-1) {
	let mx = 0;
	for (const c of g[u]) {
		if (c == p) continue;
		const tm = dfs(c, u);
		mp[key(c, u)] = tm + 1;
		//console.log('***', c, u, mp[key(c, u)]);
		mx = Math.max(mx, tm);
	}
	return mx + 1;
}

function dfs2 (u=0, p=-1, inCost=0) {
	mp[key(p, u)] = inCost;

	const cur = [];
	cur.push(1);
	for (const c of g[u]) {
		cur.push(mp[key(c, u)]);
		//console.log(c, u, mp[key(c, u)]);
	}
	cur.sort((x, y) => y - x);

	//console.log({u, cur, k})
	if (cur[1] <= k) ans--;

	for (const c of g[u]) {
		if (c == p) continue;
		const outCost = mp[key(c, u)] == cur[0] ? cur[1] : cur[0];
		dfs2(c, u, outCost + 1);
	}
}

function main () {
	let T = rn();
	while (T--) {
		rl();
		[n, k] = rna();
		g = Array.from(Array(n), _ => []);
		for (let i = 0; i < n - 1; i++) {
			let [u, v] = rna(); u--, v--;
			g[u].push(v);
			g[v].push(u);
		}

		mp = [];
		ans = n;
		dfs();
		dfs2();

		console.log(ans);
	}
}


Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle:  its vertices have integer coordinates,  the coordinates of vertices are non-negative, and  its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line $$$y = 0$$$ walking along some straight line, without crossing the interior of the triangle.  In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. Each test case contains three lines, each of them contains two integers $$$x_i$$$, $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^9$$$) — coordinates of the vertices of the downtown's border.

For each test case print a single number — the answer to the problem. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally let your answer be $$$a$$$, jury answer be $$$b$$$. Your answer will be considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$$$.

NoteIn the picture, the downtowns of the first three test cases are illustrated. Triangles are enumerated according to the indices of test cases they belong to.  In the first two test cases, all points on the borders of the downtowns are safe, thus the answers are $$$0$$$.In the following picture unsafe points for the third test case are marked with black color:  In the fourth test case, all points on the border of the downtown are safe.

function solve(input) {
    input.forEach(e => {
        const dots = e.map(data => data.split(' '));
        // console.log(dots)

        const setDotsY = new Set(dots.map(data => data[1]));
        const arrDotsY = [...setDotsY];
        if (arrDotsY.length === 2) {
            const a = countObj(dots.map(data => data[1]), arrDotsY[0]);
            const b = countObj(dots.map(data => data[1]), arrDotsY[1]);
            if (a > b) {
                if (parseInt(arrDotsY[0]) > parseInt(arrDotsY[1])) {
                    const x = dots.filter(data => data[1] === arrDotsY[0])
                    console.log(Math.abs(x[0][0] - x[1][0]))
                } else console.log(0);
            } else {
                if (parseInt(arrDotsY[1]) > parseInt(arrDotsY[0])) {
                    const x = dots.filter(data => data[1] === arrDotsY[1])
                    console.log(Math.abs(x[0][0] - x[1][0]))
                }
                else console.log(0);
            }
        } else if (arrDotsY.length === 1) {
            console.log(0)
        } else {
            console.log(0);
        }
    });
}

const countObj = (arr, val)  => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);

/** =========== DEFAULT FORMAT ==============
 *
 *  */
function set_n_line() {
    // set return 0 if the problem needs dynamic n line inputs
    // set return n > 0 if the problem needs fixed n  line inputs
    return 3
}
const readline = require('readline').createInterface({ input: process.stdin });
let inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();
function fillInput(line) {
    // dynamic n_line
    if (n_line_subinput == 0) n_line_subinput = parseInt(line)
    else if (sub_input.length < n_line_subinput) {
        sub_input.push(line)
        if (sub_input.length == n_line_subinput) {
            inputs.push(sub_input); sub_input = [];
            n_line_subinput = set_n_line();
        }
    }
}

readline.on('line', line => {
    if (t == 0) t = parseInt(line)
    else if (inputs.length < t) {
        fillInput(line)
        if (inputs.length == t) { solve(inputs);readline.close() }
    }
});
/* =========== DEFAULT FORMAT END ============== */

'use strict';

function solve(a) {
  for (let i = 0; i < 3; i++) {
    const x = a[i];
    for (let j = i + 1; j < 3; j++) {
      const y = a[j],
            z = a.find((_, k) => k !== i && k !== j);
      if (x[1] === y[1] && x[1] !== 0 && z[1] < x[1]) return Math.abs(x[0] - y[0]);
    }
  }
  return 0;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const a = [];
      let tmp = 3;
      while (tmp--) {
        a.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(s => s.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 [x1, y1] = readline().split(' ').map(Number);
        let [x2, y2] = readline().split(' ').map(Number);
        let [x3, y3] = readline().split(' ').map(Number);

        if (y1 !== y2 && y1 !== y3 && y2 !== y3) {
            output(0);
        } else if (y1 === y2 && y3 < y1) {
            output(Math.abs(x1 - x2));
        } else if (y1 === y3 && y2 < y1) {
            output(Math.abs(x1 - x3));
        } else if (y2 === y3 && y1 < y2) {
            output(Math.abs(x2 - x3));
        } else {
            output(0);
        }
    }
}

'use strict';
const { throws } = require('assert');

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

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

const MOD = 1e9+7;

let sqr = x=>x*x;
let dist = (p1, p2)=>{
  return Math.sqrt(sqr(p1.x-p2.x)+sqr(p1.y-p2.y));
};

const calc = (arr)=>{
  let ans = 0;
  for (let i=0; i<3; i++){
    for (let j=i+1; j<3; j++){
      if (arr[i].y==arr[j].y){
        for (let k=0; k<3; k++){
          if (k==i || k==j) continue;
          if (arr[k].y<arr[j].y){
            ans += dist(arr[i], arr[j])
          }
        }
      }
    }
  }
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let arr = [];
      for (let i=0; i<3; i++){
        let [x, y] = ra();
        arr.push({x, y});
      }
      print(calc(arr));
    }
}

E.calc = calc;

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var x1 = nextInt();
		var y1 = nextInt();
		var x2 = nextInt();
		var y2 = nextInt();
		var x3 = nextInt();
		var y3 = nextInt();
		if(y1 == y2){
			if(y3 < y1){
				myout(Math.abs(x1 - x2));
			}else{
				myout(0);
			}
		}else if(y1 == y3){
			if(y2 < y1){
				myout(Math.abs(x1 - x3));
			}else{
				myout(0);
			}
		}else if(y2 == y3){
			if(y1 < y2){
				myout(Math.abs(x2 - x3));
			}else{
				myout(0);
			}
		}else{
			myout(0);
		}
	}
}

function solve(input) {
    input.forEach(e => {
        const dots = e.map(data => data.split(' '));
        // console.log(dots)

        const setDotsY = new Set(dots.map(data => data[1]));
        const arrDotsY = [...setDotsY];
        if (arrDotsY.length === 2) {
            const a = countObj(dots.map(data => data[1]), arrDotsY[0]);
            const b = countObj(dots.map(data => data[1]), arrDotsY[1]);
            if (a > b) {
                if (parseInt(arrDotsY[0]) > parseInt(arrDotsY[1])) console.log(arrDotsY[0])
                else console.log(0);
            } else {
                if (parseInt(arrDotsY[1]) > parseInt(arrDotsY[0])) console.log(arrDotsY[1])
                else console.log(0);
            }
        } else if (arrDotsY.length === 1) {
            console.log(0)
        } else {
            console.log(0);
        }
    });
}

const countObj = (arr, val)  => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);

/** =========== DEFAULT FORMAT ==============
 *
 *  */
function set_n_line() {
    // set return 0 if the problem needs dynamic n line inputs
    // set return n > 0 if the problem needs fixed n  line inputs
    return 3
}
const readline = require('readline').createInterface({ input: process.stdin });
let inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();
function fillInput(line) {
    // dynamic n_line
    if (n_line_subinput == 0) n_line_subinput = parseInt(line)
    else if (sub_input.length < n_line_subinput) {
        sub_input.push(line)
        if (sub_input.length == n_line_subinput) {
            inputs.push(sub_input); sub_input = [];
            n_line_subinput = set_n_line();
        }
    }
}

readline.on('line', line => {
    if (t == 0) t = parseInt(line)
    else if (inputs.length < t) {
        fillInput(line)
        if (inputs.length == t) { solve(inputs);readline.close() }
    }
});
/* =========== DEFAULT FORMAT END ============== */

function solve(input) {
    input.forEach(e => {
        const dots = e.map(data => data.split(' '));
        // console.log(dots)

        const setDotsY = new Set(dots.map(data => data[1]));
        const arrDotsY = [...setDotsY];
        if (arrDotsY.length === 2) {
            const a = countObj(dots.map(data => data[1]), arrDotsY[0]);
            const b = countObj(dots.map(data => data[1]), arrDotsY[1]);
            if (a > b) {
                if (parseInt(arrDotsY[0]) > parseInt(arrDotsY[1])) console.log(arrDotsY[0])
                else console.log(0);
            } else {
                if (parseInt(arrDotsY[1]) > parseInt(arrDotsY[0])) console.log(arrDotsY[1])
                else console.log(0);
            }
        } else if (arrDotsY.length === 1) {
            console.log(arrDotsY[0])
        } else {
            console.log(0);
        }
    });
}

const countObj = (arr, val)  => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);

/** =========== DEFAULT FORMAT ==============
 *
 *  */
function set_n_line() {
    // set return 0 if the problem needs dynamic n line inputs
    // set return n > 0 if the problem needs fixed n  line inputs
    return 3
}
const readline = require('readline').createInterface({ input: process.stdin });
let inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();
function fillInput(line) {
    // dynamic n_line
    if (n_line_subinput == 0) n_line_subinput = parseInt(line)
    else if (sub_input.length < n_line_subinput) {
        sub_input.push(line)
        if (sub_input.length == n_line_subinput) {
            inputs.push(sub_input); sub_input = [];
            n_line_subinput = set_n_line();
        }
    }
}

readline.on('line', line => {
    if (t == 0) t = parseInt(line)
    else if (inputs.length < t) {
        fillInput(line)
        if (inputs.length == t) { solve(inputs);readline.close() }
    }
});
/* =========== DEFAULT FORMAT END ============== */

function solve(input) {
    input.forEach(e => {
        const dots = e.map(data => data.split(' '));
        // console.log(dots)

        const setDotsY = new Set(dots.map(data => data[1]));
        const arrDotsY = [...setDotsY];
        if (arrDotsY.length === 2) {
            const a = countObj(dots.map(data => data[1]), arrDotsY[0]);
            const b = countObj(dots.map(data => data[1]), arrDotsY[1]);
            if (a > b) {
                console.log(arrDotsY[0])
            } else {
                console.log(arrDotsY[1])
            }
        } else if (arrDotsY.length === 1) {
            console.log(arrDotsY[0])
        } else {
            console.log(0);
        }
    });
}

const countObj = (arr, val)  => arr.reduce((a, v) => (v == val ? a + 1 : a), 0);

/** =========== DEFAULT FORMAT ==============
 *
 *  */
function set_n_line() {
    // set return 0 if the problem needs dynamic n line inputs
    // set return n > 0 if the problem needs fixed n  line inputs
    return 3
}
const readline = require('readline').createInterface({ input: process.stdin });
let inputs = []; let sub_input = []; let t = 0; let n_line_subinput = set_n_line();
function fillInput(line) {
    // dynamic n_line
    if (n_line_subinput == 0) n_line_subinput = parseInt(line)
    else if (sub_input.length < n_line_subinput) {
        sub_input.push(line)
        if (sub_input.length == n_line_subinput) {
            inputs.push(sub_input); sub_input = [];
            n_line_subinput = set_n_line();
        }
    }
}

readline.on('line', line => {
    if (t == 0) t = parseInt(line)
    else if (inputs.length < t) {
        fillInput(line)
        if (inputs.length == t) { solve(inputs);readline.close() }
    }
});
/* =========== DEFAULT FORMAT END ============== */

'use strict';

function solve(a) {
  for (let i = 0; i < 3; i++) {
    const x = a[i];
    for (let j = i + 1; j < 3; j++) {
      const y = a[j];
      if (x[1] === y[1] && x[1] !== 0) return Math.abs(x[0] - y[0]);
    }
  }
  return 0;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const a = [];
      let tmp = 3;
      while (tmp--) {
        a.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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


The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.

The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999).

Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      if (f + fss == p + pss) return p + pss
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9) && fs.filter(v => v != 9).length > 1)
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) return console.log('No solution')
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (psn > fsn)
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL)
      if (iii[1] == 1600) {
        console.log(iii.reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join('')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[1] == 1600) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = `${v}-${iii[i]}`
          return m
        }, []).map(l => l.join(' ')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      if (f + fss == p + pss) return p + pss
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL)
      if (iii[1] == 1600) {
        console.log(iii.reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = `${iii[i]}-${v}`
          return m
        }, []).map(l => l.join(' ')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) return console.log('No solution')
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      if (fss == pss) return pss
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      if (f + fss == p + pss) return pss
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1600) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = `${iii[i]}-${v}`
          return m
        }, []).map(l => l.join(' ')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1600) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = `${v}-${iii[i]}`
          return m
        }, []).map(l => l.join(' ')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL).slice(1)
      if (iii[0] == 1081) {
        console.log(rr.slice(-50).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join(' ')).join('\n'), iii.slice(rr.length - 3, rr.length + 3))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (psn > fsn && ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL)
      if (iii[1] == 1600) {
        console.log(rr.slice(-100).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join('')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f) {
      const iii = ipt.split(EOL)
      if (iii[1] == 1600) {
        console.log(rr.slice(-150).reduce((m, v, i) => {
          if (!m[i / 100 | 0]) m[i / 100 | 0] = []
          m[i / 100 | 0][i % 100] = v
          return m
        }, []).map(l => l.join('')).join('\n'))
      }
      return console.log('No solution')
    }
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})

'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)
  ils[0] = '1000'

  const rr = []

  for (let i = 1; i < ils.length; i++) {
    const p = ils[i - 1]
    const c = ils[i]
    const f = best(p, c)
    if (!f)return console.log('No solution')
    rr.push(f)
    ils[i] = f
  }

  console.log(rr.join('\n'))

  function best (p, f) {
    let [f1, f2, f3, f4] = f.split('')
    let [p1, p2, p3, p4] = p.split('')
    if (p1 == 0) {
      if (+`${f2}${f3}${f4}` >= +`${p2}${p3}${p4}`)
        return `1${f2}${f3}${f4}`
      else
        return `2${f2}${f3}${f4}`
    }

    let res = search([p1, p2, p3, p4], [f1, f2, f3, f4])

    return test(p, res.split('')) && res

    function search ([p, ...ps], [f, ...fs]) {
      if (!ps.length) {
        return p
      }
      let fss = fs.join('')
      let pss = ps.join('')
      let psn = +pss
      let fsn = +fss
      let pn = +p
      let fn = +f
      if (pn > fn || pn + 1 < fn) {
        if (psn > fsn) {
          return pn + 1 + fss
        } else {
          return pn + fss
        }
      } else if (pn + 1 == fn) {
        if (psn <= fsn) {
          return pn + fss
        } else {
          for (let i = 0; i < fs.length; i++) {
            if (fs[i] != 0) {
              fs[i] = 0
              break
            }
          }
          return f + fs.join('')
        }
      } else { // pn == fn
        if (ps.every(v => v == 9))
          return pn + 1 + fss
        return f + search(ps, fs)
      }
    }

    function test(p, fs) {
      if (fs.length > 4) return
      let f = +fs.join('')
      if (f < +p) return
      if (f < 1000) return
      if (f > 2011) return
      return true
    }
  }
})


Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a1, a2, ..., an and b1, b2, ..., bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.Well, she almost had it all — each of the sequences a and b matched exactly n - 1 elements in Sengoku's permutation. In other words, there is exactly one i (1 ≤ i ≤ n) such that ai ≠ pi, and exactly one j (1 ≤ j ≤ n) such that bj ≠ pj.For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.

The first line of input contains a positive integer n (2 ≤ n ≤ 1 000) — the length of Sengoku's permutation, being the length of both meteor outbursts at the same time. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the sequence of colours in the first meteor outburst. The third line contains n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ n) — the sequence of colours in the second meteor outburst. At least one i (1 ≤ i ≤ n) exists, such that ai ≠ bi holds.

Output n space-separated integers p1, p2, ..., pn, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them. Input guarantees that such permutation exists.

NoteIn the first sample, both 1, 2, 5, 4, 3 and 1, 2, 3, 4, 5 are acceptable outputs.In the second sample, 5, 4, 2, 3, 1 is the only permutation to satisfy the constraints.

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

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

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

var ax = [];
var bx = [];
var current = 0;

var mem = [];
var remain = [];
var result1 = [];
var result2 = [];

for(var i = 0; i < a.length; i++) {
	if(a[i] == b[i]){
		result1[i] = a[i];
		result2[i] = a[i];
		mem[a[i]] = 1;
	} else {
		result1[i] = 0;
		result2[i] = 0;
	}
}

for(var i = 1; i <= n; i++) {
	if(mem[i] != 1) {
		remain.push(i);
	}
}

for(var i = 0; i < a.length; i++) {
	if(a[i] != b[i]){
		if(current == 0) {
			result1[i] = remain[0];
			result2[i] = remain[1];
			current++;
		} else {
			result1[i] = remain[1];
			result2[i] = remain[0];
		}
	}
}

var numA = 0;
var numB = 0;
for(var i = 0; i < a.length; i++) {
	if(a[i] == result1[i])
		numA++;
	if(b[i] == result1[i])
		numB++;
}

if(numA == n-1 && numB == n-1) {
	for(var i = 0; i < a.length; i++)
		write(result1[i] + ' ');
} else {
	for(var i = 0; i < a.length; i++)
		write(result2[i] + ' ');
}


You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it.Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\frac n 2$$$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of string $$$s$$$. The second line is the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

Print "NO" if there is no diverse substring in the string $$$s$$$. Otherwise the first line should contain "YES". The second line should contain any diverse substring of string $$$s$$$.

NoteThe first example has lots of correct answers. Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer.

const readline = require('readline');

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

let n;
rl.on('line', function(line){
	if (!n) {
		n = parseInt(line);
	} else {
		const s = line;
		let i = 0;
		while (s[i] === s[i + 1] && i < s.length) {
			i++;
		}
		if (i < s.length - 1) {
			console.log('YES');
			console.log(s.substr(i, 2));
		} else {
			console.log('NO');
		}
		rl.close();
	}
});

process.stdin.on('data', function(chunk){
	var lns = chunk.toString().replace(/\r/g, "").split(/\n/),r;
	(r = lns[1].match(/(.)(?!\1)/g)).length > 1 ? console.log('YES\n' + r[0] + r[1]) : console.log('NO');
});

const readline = require('readline');

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

let counter=0, N

rl.on('line', (input) => {
   if(counter==0){
      N=parseInt(input);
      counter++;
   }
   else
   {
       let ans="NO", helper="";
       for(let i=0; i<N-1; i++){
           if(input[i]!=input[i+1]){
               ans="YES";
               helper=input.substr(i,2);
;               break;
           }
       }
       console.log(ans);
       console.log(helper);
       rl.close();
   }

  });

readline();
var str = readline(), answer;
for(var i = 1; i < str.length; i++) {
    if(str[i] !== str[i-1]) {
        answer = str[i-1] + str[i];
        break;
    }
}

if(answer) {
    print('YES');
    print(answer);
} else {
    print('NO');
}

var length = readline();
var text = readline();
  var answer = "";
  for (var i = 0; i < length - 1; i ++) {
      var firstChar = text.charAt(i);
      var secondChar = text.charAt(i + 1);

    if (firstChar != secondChar) {
      answer = firstChar + secondChar;
      break;
    }
  }

  if (answer === "") {
    write("NO");
  } else {
    write("YES\n");
    write(answer);
  }

process.stdin.on('data', function(chunk){
	var lns = chunk.toString().replace(/\r/g, "").split(/\n/),r;
	(r = lns[1].match(/(.)(?!\1)(?!$)/g)) ? console.log('YES\n' + r[1] + r[2]) : console.log('NO');
});

var length = readline();
var text = readline();
var charStartIndex = 97;
var charIndexArray = [];

for (var i = 0; i < length; i ++) {
    var charCode = text.charAt(i).charCodeAt(0);
    if (charIndexArray[charCode - charStartIndex] === undefined) {
       charIndexArray[charCode - charStartIndex] = 1;
    } else {
       charIndexArray[charCode - charStartIndex] += 1;
    }
}

var answer = "";
for (var i = 0; i < charIndexArray.length; i ++) {
  if (charIndexArray[i] <= charIndexArray.length / 2) {
    answer = String.fromCharCode(charIndexArray[i] + 97);
    break;
  }
}

if (answer === "") {
  write("NO");
} else {
  write("YES");
  write(answer);
}

var length = readline();
var text = readline();
var charStartIndex = 97;
var charIndexArray = [];

for (var i = 0; i < length; i ++) {
    var charCode = text.charAt(i).charCodeAt(0);
    if (charIndexArray[charCode - charStartIndex] === undefined) {
       charIndexArray[charCode - charStartIndex] = 1;
    } else {
       charIndexArray[charCode - charStartIndex] += 1;
    }
}

var answer = "";
for (var i = 0; i < charIndexArray.length; i ++) {
  if (charIndexArray[i] <= charIndexArray.length / 2) {
    answer = String.fromCharCode(charIndexArray[i] + 97);
    break;
  }
}

if (answer === "") {
  write("NO");
} else {
  write("YES\n");
  write(answer);
}

var length = readline();
var text = readline();
var charStartIndex = 97;
var charIndexArray = [];

for (var i = 0; i < length; i ++) {
    var charCode = text.charAt(i).charCodeAt(0);
    if (charIndexArray[charCode - charStartIndex] === undefined) {
       charIndexArray[charCode - charStartIndex] = 1;
    } else {
       charIndexArray[charCode - charStartIndex] += 1;
    }
}

for (var i = 0; i < charIndexArray.length; i ++) {
  if (charIndexArray[i] <= charIndexArray.length / 2) {
    write("YES");
    write(String.fromCharCode(charIndexArray[i] + 97));
  }
}

write("NO");


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to $$$1$$$. In one operation, you can do the following: Select an arbitrary index in the array $$$1 \leq i \leq n$$$; Make $$$a_i = \gcd(a_i, i)$$$, where $$$\gcd(x, y)$$$ denotes the GCD of integers $$$x$$$ and $$$y$$$. The cost of such an operation is $$$n - i + 1$$$.You need to find the minimum total cost of operations we need to perform so that the GCD of the all array numbers becomes equal to $$$1$$$.

Each test consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5\,000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 20$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.

For each test case, output a single integer — the minimum total cost of operations that will need to be performed so that the GCD of all numbers in the array becomes equal to $$$1$$$. We can show that it's always possible to do so.

NoteIn the first test case, the GCD of the entire array is already equal to $$$1$$$, so there is no need to perform operations.In the second test case, select $$$i = 1$$$. After this operation, $$$a_1 = \gcd(2, 1) = 1$$$. The cost of this operation is $$$1$$$.In the third test case, you can select $$$i = 1$$$, after that the array $$$a$$$ will be equal to $$$[1, 4]$$$. The GCD of this array is $$$1$$$, and the total cost is $$$2$$$.In the fourth test case, you can select $$$i = 2$$$, after that the array $$$a$$$ will be equal to $$$[3, 2, 9]$$$. The GCD of this array is $$$1$$$, and the total cost is $$$2$$$.In the sixth test case, you can select $$$i = 4$$$ and $$$i = 5$$$, after that the array $$$a$$$ will be equal to $$$[120, 60, 80, 4, 5]$$$. The GCD of this array is $$$1$$$, and the total cost is $$$3$$$.

const fs = require("fs");

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

const testCases = [];
let T;

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

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

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

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, a } = testCase;
  // console.log(n, a);
  let g = a[0];
  for (let i = 1; i < n; i++) g = gcd(g, a[i]);

  if (g == 1) {
    console.log(0);
    return;
  }

  for (let i = 0; i < n; i++) {
    a[i] = gcd(g, i + 1);
  }

  let result = Infinity;

  const check = (gg, ind, val) => {
    // console.log("check", gg, ind, val);
    if (gg == 1) {
      if (val < result) result = val;
      return;
    }
    if (ind == 0) return;

    check(gg, ind - 1, val);
    check(gcd(gg, a[ind - 1]), ind - 1, val + n - ind + 1);
  };

  check(g, n, 0);
  console.log(result);
}

parseInput();

testCases.forEach(solution);

function solve() {
    var n = Number(read());
    var a = readArray(Number);
    var allGcd = a[0];
    for (var i = 1; i < n; i++) {
        allGcd = gcd(allGcd, a[i]);
    }
    if (allGcd === 1) {
        write(0);
        return;
    }
    if (gcd(allGcd, n) === 1) {
        write(1);
        return;
    }
    if (gcd(allGcd, n - 1) === 1) {
        write(2);
        return;
    }
    write(3);
}

function start() {
    var T = 1;
    T = Number(read());
    for (var t = 0; t < T; t++) {
        solve();
    }
    writeAns();
}

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

var MEMORY;
var MEMORY_INDEX = 0;
var ANS = '';

try {
    initInput(start);
} catch (e) {
    console.log(e);
}
function readArray(f) {
    return read().split(' ').map(f);
}

function sortNumbers(a, b) {
    return a - b;
}
function sortNumbersDec(a, b) {
    return b - a;
}
var ANS;
// вывод через ANS быстрее, но ест кучу памяти.
// К тому же, максимальная длина строки - 2097151.
function write(value) {
    // console.log(value);
    ANS += value + '\n';
}
function writeAns() {
    if (ANS) {
        console.log(ANS);
    }
}
function read() {
    return MEMORY[MEMORY_INDEX++];
}
function initInput(callback) {
    var fs = require('fs');
    var isLocalStart = process.argv[2] === 'lorelvate';
    if (!isLocalStart) {
        MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
        callback();
        return;
    }
    var path = require('path');
    fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {
        if (err) {
            write(err);
            return;
        }
        MEMORY = data.split('\r\n');
        callback();
    });
}

const fs = require("fs");

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

const testCases = [];
let T;

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

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

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

    testCases.push(testCase);
  }
}

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

  let g = a[0];
  for (let i = 1; i < n; i++) g = gcd(g, a[i]);

  // console.log("gcd", g);

  let result = 0;
  let i = n;
  while (g != 1) {
    // console.log("while", i);
    const gg = gcd(g, i);
    if (gg != g) {
      // console.log("Found", g, gg, i, n, n - i + 1);
      g = gg;
      result += n - i + 1;
    }
    i--;
  }

  console.log(result);
}

parseInput();

testCases.forEach(solution);