The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids:  after the $$$1$$$-st day it will belong to the $$$5$$$-th kid,  after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid,  after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid,  after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 200$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 200$$$) — the number of kids in the query. The second line of the query contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct, i.e. $$$p$$$ is a permutation), where $$$p_i$$$ is the kid which will get the book of the $$$i$$$-th kid.

For each query, print the answer on it: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the number of the day the book of the $$$i$$$-th child is returned back to him for the first time in this query.

//6
//4 6 2 1 5 3

// let p = [4,6,2,1,5,3];

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

let inputString = '';
let currentLine = 0;

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

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

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

function main() {
    let t = readline();
    while (t > 0) {
        let n = readline();
        let p = readline().split(' ');

        b1(n, p);

        t--;
    }
}

function b1(n, p) {
    const travel = [];
    const ans = [];

    for(let i = 0; i < n; i++) {
        p[i] = p[i] - 1;
    }

    let c = 0;
    while(c < n) {
        if(!travel[c]) {
            let r = [];
            let s = p[c];
            while(!travel[c]) {
                travel[s] = true;
                r.push(s);
                s = p[s];
            }
            for(let i = 0;i < r.length;i++)
                ans[r[i]] = r.length;
        }
        c++;
    }

    let r ='';
    for(let i = 0; i < ans.length; i++) {
        if(i == 0)
            r += '' + ans[i];
        else
            r += ' ' + ans[i];
    }
     console.log(r);
}

//6
//4 6 2 1 5 3

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

let inputString = '';
let currentLine = 0;

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

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

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

function main() {
    let t = readline();
    while (t > 0) {
    let n = readline();
    let p = readline().split(' ');

    b1(n,p);

    t--;
    }
}

function create2DArray(len) {
    let b = [];
    for (var i = 0; i < +len; i++) {
        b[i] = new Array(+len).fill(0);
    }
    return b;
}

function b1(n,p) {
    let b = create2DArray(n);
    let q = 0;
    let s = 0;
    let r = '';
    while (q < p.length) {
        let i = p[s] - 1;

        if (b[i][q] && i != q) {
            b[q][q] += (b[i][q] + 1);
            q++;
            s = q;
            continue;
        } else {
            b[q][q] += 1;
            b[q][i] = b[q][q];

            if (q == i) {
                // console.error('Result2', q, b[q][q]);
                q++;
                s = q;
                continue;
            }
        }
        s = i;
    }

    for(let i = 0; i < p.length; i++) {
        if(i == 0)
            r += '' + b[i][i];
        else
            r += ' ' + b[i][i];
    }
     console.log(r);
}

//6
//4 6 2 1 5 3

// let p = [4,6,2,1,5,3];

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

let inputString = '';
let currentLine = 0;

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

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

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

function main() {
    let t = readline();
    while (t > 0) {
    let n = readline();
    let p = readline().split(' ');

    b1(n,p);

    t--;
    }
}

function create2DArray(len) {
    let b = {};
    for (var i = 0; i < +len; i++) {
        b[i] = {};
    }
    return b;
}

function b1(n,p) {
    let b = create2DArray(n);
    let q = 0;
    let s = 0;
    let r = '';
    while (q < p.length) {
        let i = p[s] - 1;

        if (b[i][q] && i != q) {
            b[q][q] = (b[q][q] || 0) + (b[i][q] + 1);
            q++;
            s = q;
            continue;
        } else {
            b[q][q] = (b[q][q] || 0) + 1;
            b[q][i] = b[q][q];

            if (q == i) {
                // console.error('Result2', q, b[q][q]);
                q++;
                s = q;
                continue;
            }
        }
        s = i;
    }

    for(let i = 0; i < p.length; i++) {
        if(i == 0)
            r += '' + b[i][i];
        else
            r += ' ' + b[i][i];
    }
     console.log(r);
}

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

    function foo (data, n) {

        function per(value, index, array, count = 1, startVindex = index) {
            if (startVindex + 1 === array[index]) return count;
            return per(value, array[index] - 1, array, ++count, startVindex);
        }

        return data.map((value, index, array) => {
            const result = per(value, index, array);
            return result;
        }).join(' ');
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ").map(Number);
        let n = lines[testCount * 2 - 1].split(" ").map(Number);

        let result = foo(data, n);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);
})

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

    let inputString = '';
    let currentLine = 0;

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

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

        main();
    });

    function readAllLine() {
        return inputString;
    }
    function findNextArray(originArray, mapArray) {
        let arReturn = [];
        for (let i = 0; i < originArray.length; i++) {
            arReturn.push(originArray[mapArray[i]-1]);
        }
        return arReturn;
    }

    function resolve(arKids) {
        // console.log(arKids.join(" "));
        // return arKids;
        let _arKids = [...arKids];
        let arBeforeMatchByDate = arKids;
        let tmp = [], arReturn = [], fullReturnCount = 0, dayCount = 0;
        let arBefore1Day = [];
        for(let i = 0;i < arKids.length; i++) {
            arBefore1Day[arKids[i] - 1] = (i + 1).toString();
        }
        while (fullReturnCount < arKids.length) {
            dayCount++;
            tmp = [];
            //Build array current Date time
            for (let i = 0; i < arKids.length; i++) {
                let currentBookIndex = arKids[i];
                if (dayCount > 1) {
                    currentBookIndex = arKids[_arKids[i] - 1];
                }
                tmp.push(currentBookIndex);
                if (currentBookIndex == i + 1 && !arReturn[i]) {
                    arReturn[i] = dayCount;
                    fullReturnCount++;
                } else if(arBeforeMatchByDate[i] == currentBookIndex
                    && !arReturn[i] && (dayCount > 1)) {
                    //Compare With ArrayBefore Match
                    arReturn[i] = dayCount * 2 - 1;
                    fullReturnCount++;
                }
            }
            //Build Array Before N day to match
            if (dayCount > 1) {
                arBeforeMatchByDate = findNextArray(arBefore1Day, arBeforeMatchByDate)
            } else {
                arBeforeMatchByDate = [...arBefore1Day];
            }
            for(let i = 0; i < arBeforeMatchByDate.length; i ++) {
                if(arBeforeMatchByDate[i] == tmp[i] && !arReturn[i]) {
                    arReturn[i] = dayCount * 2;
                    fullReturnCount++;
                }
            }

            _arKids = [...tmp];
        }
        console.log(arReturn.join(" "));
        return arReturn;
    }

    function createTestCase(maxRange) {
        let arTestCase = [];
        for (let i = 0; i < maxRange; i++) {
            arTestCase.push(i === maxRange - 1 ? 1 : i + 2);
        }
        fs.appendFile('testcase.txt', '1\n', function (err) {
            if (err) throw err;
        });
        fs.appendFile('testcase.txt', maxRange+'\n', function (err) {
            if (err) throw err;
        });
        fs.appendFile('testcase.txt', arTestCase.join(' '), function (err) {
            if (err) throw err;
        });
    }

    function main() {
        let start = Date.now();
        const data = readAllLine();
        let arTestCase = [];
        if (data.length > 0) {
            const numberOfQueues = data.shift();
            let count = 0;
            while (data.length > 0 && count <numberOfQueues) {
                count++
                let numberOfStudents = data.shift();
                let arStudent = data.shift().split(' ').slice(0, numberOfStudents);
                arTestCase.push(
                    arStudent
                );
            }
        }
        if(arTestCase.length > 0) {
            for(let i = 0;i < arTestCase.length; i++) {
                resolve(arTestCase[i])
            }
        }
        // console.log(Date.now() - start);

    }

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

var gcd = (a, b) => a ? gcd(b % a, a) : b;
var lcm = (a, b) => a * b / gcd(a, b);

var a,cnt;
function main(){
	let t =+(readLine());
	while(t--){
		let n = +(readLine())
		a = readLine().split(" ").map(Number);
		// console.log(a)
		for(let i = 0; i<n ;i++){
			cnt=1;
			process.stdout.write(rec(i,a[i])+' ');
		}
		console.log()
	}
}

function rec(f,c){
	if((f+1)==c){
		return cnt;
	}
	else{
		cnt++;
		return rec(f,a[c-1],cnt);
	}
}

t = +readline();
res = '';
while (t-->0){
    n = +readline();
    ar = readline().split(' ').map(Number);
    for (i = 0;i<n;i++){
        count = 1;
        pos = i;
        while (ar[pos] != (i+1)){
            pos = ar[pos] - 1;
            count++;
        }
        res += count+' ';
    }
    res += '\n';
}
print(res);

//-------------------------field fun--------------------------
    var _tmp = [];
    var _front = 0;
    var readOne = function() {
        if(_front >= _tmp.length) {
            _tmp = readline().split(' ');
            _front = 0;
            return readOne();
        } else {
            return _tmp[_front++];
        }
    };
    var readInt = function() {
        return parseInt(readOne());
    };
    var readStr = function() {
        return readOne();
    };
    //-----------------------field program------------------------
    var fa = [];
    var nums = [];
    var Fa = function(n) {
        if(fa[n] != n) {
            fa[n] = Fa(fa[n]);
        }
        return fa[n];
    };
    var q = readInt();
    while(q--) {
        fa = [];
        nums = [];
        var n = readInt();
        for(var i = 1; i <= n; i++) {
            fa[i] = i;
            nums[i] = 1;
        }
        for(var i = 1; i <= n; i++) {
            var t = readInt();
            if(Fa(i) != Fa(t)) {
                nums[fa[t]] += nums[fa[i]];
                fa[fa[i]] = fa[t];
            }
        }
        for(var i = 1; i <= n; i++) {
            write(nums[Fa(i)] + ' ');
        }
        write('\n');
    }

'use strict'
let input = readline()
let i = 1
let daysHold =1
let final = []
while(i <= input){
    let secondLine = readline()
    let arr = readline().split(' ').map(Number)
    let copy = JSON.parse(JSON.stringify(arr))
    let j = 0
    while(j < arr.length){

        while(1){
            if(arr[j] !== j+1){
                let temp = arr[arr[j]-1]
                arr[arr[j]-1] = arr[j]
                arr[j] = temp
                daysHold++
            }
            else if(arr[j] == j+1) break
        }
        final.push(daysHold)
        daysHold = 1
        arr = JSON.parse(JSON.stringify(copy))
        j++
    }
    print(final.join(' '))
    final = []
    i++
}

'use strict'

const problem = (n, a) => {
    const b = Array(n).fill(0);
    let i;
    while ((i = b.indexOf(0)) !== -1) {
        let j = i, r = [ j ];
        while (i !== (j = a[j])) r.push(j);
        r.forEach(j => b[j] = r.length);
    }
    return b.join(' ');
}

let q = +readline();
while(q--) {
    print(problem(+readline(), readline().split(' ').map(i => +i - 1)));
}

'use strict'

const problem = (n, a) => {
    const b = Array(n).fill(0);
    for (let i = 0; i < n; i++) {
        if (b[i]) continue;
        let j = i, r = [ i ];
        while((j = a[j]) !== i) r.push(j);
        r.forEach(i => b[i] = r.length);
    }
    return b.join(' ');
}

for (let q = +readline(); q; q--) print(problem(+readline(), readline().split(' ').map(i => --i)));

//6
//4 6 2 1 5 3

// let p = [1,2,3,4,5,6];

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

let inputString = '';
let currentLine = 0;

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

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

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

function main() {
    let t = readline();
    while (t > 0) {
        let n = readline();
        let p = readline().split(' ');

        b1(n, p);

        t--;
    }
}

function b1(n, p) {
    const travel = [];
    const ans = [];

    for(let i = 0; i < n; i++) {
        p[i] = p[i] - 1;
    }

    let c = 0;
    while(c < n) {
        if(!travel[c]) {
            let r = [];
            let s = p[c];
            while(!travel[c]) {
                travel[s] = true;
                r.push(s);
                s = p[s];
            }
            for(let i = 0;i < r.length;i++)
                ans[r[i]] = r.length;
        }
        c++;
    }

    let r ='';
    for(let i = 0; i < ans.length; i++) {
        if(i == 0)
            r += '' + ans[i];
        else
            r += ' ' + ans[i];
    }
     console.log(r);
}

// b1(6,p)

//6
//4 6 2 1 5 3

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

let inputString = '';
let currentLine = 0;

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

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

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

function main() {
    let t = readline();
    while (t > 0) {
    let n = readline();
    let p = readline().split(' ');

    b1(n,p);

    t--;
    }
}

function create2DArray(len) {
    let b = []
    for (var i = 0; i < len; i++) {
        b[i] = new Array(9).fill(0);
    }
    return b;
}

function b1(n,p) {

    let b = create2DArray(n);
    let q = 0;
    let s = 0;
    let r = '';
    while (q < p.length) {
        let i = p[s] - 1;

        if (b[i][q] && i != q) {
            b[q][q] += (b[i][q] + 1);
            q++;
            s = q;
            continue;
        } else {
            b[q][q] += 1;
            b[q][i] = b[q][q];

            if (q == i) {
                // console.error('Result2', q, b[q][q]);
                q++;
                s = q;
                continue;
            }
        }
        s = i;
    }

    for(let i = 0; i < p.length; i++) {
        if(i === 0)
            r += '' + b[i][i];
        else
            r += ' ' + b[i][i];
    }
     console.log(r);
}

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

    let inputString = '';
    let currentLine = 0;

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

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

        main();
    });

    function readAllLine() {
        return inputString;
    }
    function findNextArray(originArray, mapArray) {
        let arReturn = [];
        for (let i = 0; i < originArray.length; i++) {
            arReturn.push(originArray[mapArray[i]-1]);
        }
        return arReturn;
    }

    function resolve(arKids) {
        // console.log(arKids.join(" "));
        // return arKids;
        let _arKids = [...arKids];
        let arBeforeMatchByDate = arKids;
        let tmp = [], arReturn = [], fullReturnCount = 0, dayCount = 0;
        let arBefore1Day = [];
        for(let i = 0;i < arKids.length; i++) {
            arBefore1Day[arKids[i] - 1] = (i + 1).toString();
        }
        while (fullReturnCount < arKids.length) {
            dayCount++;
            tmp = [];
            //Build array current Date time
            for (let i = 0; i < arKids.length; i++) {
                let currentBookIndex = arKids[i];
                if (dayCount > 1) {
                    currentBookIndex = arKids[_arKids[i] - 1];
                }
                tmp.push(currentBookIndex);
                if (currentBookIndex == i + 1 && !arReturn[i]) {
                    arReturn[i] = dayCount;
                    fullReturnCount++;
                } else if(arBeforeMatchByDate[i] == currentBookIndex
                    && !arReturn[i] && (dayCount > 1)) {
                    //Compare With ArrayBefore Match
                    arReturn[i] = dayCount * 2 - 1;
                    fullReturnCount++;
                }
            }
            //Build Array Before N day to match
            if (dayCount > 1) {
                arBeforeMatchByDate = findNextArray(arBefore1Day, arBeforeMatchByDate)
            } else {
                arBeforeMatchByDate = [...arBefore1Day];
            }
            for(let i = 0; i < arBeforeMatchByDate.length; i ++) {
                if(arBeforeMatchByDate[i] == tmp[i] && !arReturn[i]) {
                    arReturn[i] = dayCount * 2;
                    fullReturnCount++;
                }
            }

            _arKids = [...tmp];
        }
        console.log(arReturn.join(" "));
        return arReturn;
    }

    function createTestCase(maxRange) {
        let arTestCase = [];
        for (let i = 0; i < maxRange; i++) {
            arTestCase.push(i === maxRange - 1 ? 1 : i + 2);
        }
        fs.appendFile('testcase.txt', '1\n', function (err) {
            if (err) throw err;
        });
        fs.appendFile('testcase.txt', maxRange+'\n', function (err) {
            if (err) throw err;
        });
        fs.appendFile('testcase.txt', arTestCase.join(' '), function (err) {
            if (err) throw err;
        });
    }

    function main() {
        let start = Date.now();
        const data = readAllLine();
        let arTestCase = [];
        if (data.length > 0) {
            const numberOfQueues = data.shift();
            let count = 0;
            while (data.length > 0 && count <numberOfQueues) {
                count++
                let numberOfStudents = data.shift();
                let arStudent = data.shift().split(' ').slice(0, numberOfStudents);
                arTestCase.push(
                    arStudent
                );
            }
        }
        if(arTestCase.length > 0) {
            for(let i = 0;i < arTestCase.length; i++) {
                resolve(arTestCase[i])
            }
        }
        console.log(Date.now() - start);

    }

//-------------------------field fun--------------------------
    var _tmp = [];
    var _front = 0;
    var readOne = function() {
        if(_front >= _tmp.length) {
            _tmp = readline().split(' ');
            _front = 0;
            return readOne();
        } else {
            return _tmp[_front++];
        }
    };
    var readInt = function() {
        return parseInt(readOne());
    };
    var readStr = function() {
        return readOne();
    };
    //-----------------------field program------------------------
    var fa = [];
    var nums = [];
    var Fa = function(n) {
        if(fa[n] != n) {
            fa[n] = Fa(fa[n]);
        }
        return fa[n];
    };
    var q = readInt();
    while(q--) {
        fa = [];
        nums = [];
        var n = readInt();
        for(var i = 1; i <= n; i++) {
            fa[i] = i;
            nums[i] = 1;
        }
        for(var i = 1; i <= n; i++) {
            var t = readInt();
            if(fa[i] != fa[t]) {
                nums[fa[t]] += nums[Fa(i)];
                fa[i] = fa[Fa(t)];
            }
        }
        for(var i = 1; i <= n; i++) {
            write(nums[Fa(i)] + ' ');
        }
        write('\n');
    }

//-------------------------field fun--------------------------
    var _tmp = [];
    var _front = 0;
    var readOne = function() {
        if(_front >= _tmp.length) {
            _tmp = readline().split(' ');
            _front = 0;
            return readOne();
        } else {
            return _tmp[_front++];
        }
    };
    var readInt = function() {
        return parseInt(readOne());
    };
    var readStr = function() {
        return readOne();
    };
    //-----------------------field program------------------------
    var fa = [];
    var nums = [];
    var Fa = function(n) {
        if(fa[n] != n) {
            fa[n] = Fa(fa[n]);
        }
        return fa[n];
    };
    var q = readInt();
    while(q--) {
        fa = [];
        nums = [];
        var n = readInt();
        for(var i = 1; i <= n; i++) {
            fa[i] = i;
            nums[i] = 1;
        }
        for(var i = 1; i <= n; i++) {
            var t = readInt();
            if(fa[i] != fa[t]) {
                nums[Fa(t)] += nums[Fa(i)];
                fa[fa[i]] = fa[t];
            }
        }
        for(var i = 1; i <= n; i++) {
            write(nums[Fa(i)] + ' ');
        }
        write('\n');
    }

'use strict'

const problem = (n, a) => {
    const b = Array(n).fill(0);
    for (let i = 0; i < n; i++) {
        if (!b[i]) {
            let j = i, r = [ i ];
            while((j = a[j]) !== i) r.push(j);
            b.forEach(i => b[i] = r.length);
        }
    }
    return b.join(' ');
}

let q = +readline();
while(q--) print(problem(+readline(), readline().split(' ').map(i => +i - 1)));

//6
//4 6 2 1 5 3

let p = [1,2,3,4,5,6];

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

// let inputString = '';
// let currentLine = 0;

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

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

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

// function main() {
//     let t = readline();
//     while (t > 0) {
//         let n = readline();
//         let p = readline().split(' ');

//         b1(n, p);

//         t--;
//     }
// }

function b1(n, p) {
    const travel = [];
    const ans = [];

    for(let i = 0; i < n; i++) {
        p[i] = p[i] - 1;
    }

    let c = 0;
    while(c < n) {
        if(!travel[c]) {
            let r = [];
            let s = p[c];
            while(!travel[c]) {
                travel[s] = true;
                r.push(s);
                s = p[s];
            }
            for(let i = 0;i < r.length;i++)
                ans[r[i]] = r.length;
        }
        c++;
    }

    let r ='';
    for(let i = 0; i < ans.length; i++) {
        if(i == 0)
            r += '' + ans[i];
        else
            r += ' ' + ans[i];
    }
     console.log(r);
}

b1(6,p)


During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $$$121, 66, 98989$$$ are palindromes, and $$$103, 239, 1241$$$ are not palindromes.Alina understands that a valid number always exist. Help her find one!

The first line of input data contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$) — the length of the number that is written on the ground. The second line of contains the positive $$$n$$$-digit integer without leading zeroes — the number itself. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100\,000$$$.

For each of $$$t$$$ test cases print an answer — a positive $$$n$$$-digit integer without leading zeros, such that the sum of the input integer and this number is a palindrome. We can show that at least one number satisfying the constraints exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case $$$99 + 32 = 131$$$ is a palindrome. Note that another answer is $$$12$$$, because $$$99 + 12 = 111$$$ is also a palindrome.In the second test case $$$1023 + 8646 = 9669$$$.In the third test case $$$385 + 604 = 989$$$.

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let n = parseInt(readline());
    let num = readline();
    print(Easy(n, num));
  }
}
function Easy(n, number) {
  let first = number[0];
  if (first == "9") {
    let str = "1";
    for (let i = 0; i < n; i++) str += "1";
    return sub(number, str);
  } else {
    let str = "";
    for (let i = 0; i < n; i++) str += "9";
    return sub(number, str);
  }
}

function sub(a, b) {
  let carry = 0;
  let i = a.length - 1;
  let j = b.length - 1;
  let ans = [];
  while (j !== -1) {
    let dig1 = Number(a[i]);
    let dig2 = Number(b[j]);
    if (!dig1) dig1 = 0;
    if (dig2 - (dig1 + carry) < 0) {
      let remain = 10 + dig2 - (dig1 + carry);
      ans[j] = remain;
      carry = 1;
    } else {
      let remain = dig2 - (dig1 + carry);
      ans[j] = remain;
      carry = 0;
    }
    i--;
    j--;
  }
  j++;
  let str = "";
  while (ans[j] == 0) j++;
  while (j !== b.length) {
    str += ans[j];
    j++;
  }
  return str;
}

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => lines[i++]
}
const int = (num, radix=10) => parseInt(num, radix)

rl.on('line', line => lines.push(line))

rl.on("close", () => {
  const readLine = createReadLine();
  let t = int(readLine());
  while (t--) {
    let n = int(readLine());
    let num = readLine();
    console.log(f(num, n));
  }
});

function f(num, n) {
  let ans = '';
  if (num[0] == '9') {
    let cnt = 0;
    for (let i = 0; i < n; i++) {
      ans += ((11 - cnt - int(num[n - i - 1])) % 10).toString()
      cnt = Math.floor((int(ans[i]) + int(num[n - i - 1])) / 10)
    }
    ans = ans.split('').reverse().join('')
  } else {
    for (let i = 0; i < n; i++) {
      ans += 9 - num[i];
    }
  }
  return ans;
}

'use strict';

function solve(n, s) {
  if (Number(s[0]) < 9) {
    const res = new Array(n);
    for (let i = n - 1; i >= 0; i--) {
      const num = Number(s[i]);
      res[i] = 9 - num;
    }
    return res.join('');
  } else {
    const res = new Array(n + 1).fill(1);
    for (let i = n - 1; i >= 0; i--) {
      const num = Number(s[i]);
      let dif = res[i + 1] - num;
      if (dif >= 0) res[i + 1] = dif;else {
        dif = 10 + dif;
        res[i]--;
        res[i + 1] = dif;
      }
    }
    return res.slice(1).join('');
  }
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const s = await read();
      res[i] = solve(n, s);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

const getPlaindrome = (k,n,fill)=>{
     let carry = 0;
     let res = "";
     for(let i=k-1;i>=0;i--){
          let num = parseInt(n[i]);
          if(carry===1) num+=1;
          if(num<=fill){
               res=fill-num+(res);
               carry = 0;
          }
          else{
               carry = 1;
               res = (11-num)+res;
          }
     }
     return res;
}
const solve = (k,n)=>{
     if(n[0]==="9") return getPlaindrome(k,n,1);
     else return getPlaindrome(k,n,9);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let k = parseInt(readline());
       let n = readline();
       console.log(solve(k,n));
  }
}
main();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        const length = parseInt(readline(), 10);
        let num = readline();
        num = ('0').repeat(length - num.length) + num;

        let result = '';

        let lessThanNinetyPercent = Number(num.charAt(0)) < 9;
        if (lessThanNinetyPercent) {
            let target = ('9').repeat(length);
            for (let i = 0; i < length; i++) {
                result += Number(target.charAt(i)) - Number(num.charAt(i));
            }
            output(result);
            continue;
        } else {
            let reverseResult = '';
            let carryOver = false;
            for (let i = length - 1; i >= 0; i--) {
                let digit = Number(num.charAt(i));
                if (carryOver) {
                    digit++;
                    carryOver = false;
                    if (digit === 10) {
                        carryOver = true;
                        digit = 0;
                    }
                }
                if (digit === 0) {
                    reverseResult += '1';
                } else if (digit === 1) {
                    reverseResult += '0';
                } else {
                    reverseResult += String(11 - digit);
                    carryOver = true;
                }
            }
            result = reverseResult.split('').reverse().join('');
            output(result);
            continue;
        }

    }
}

var t = readline();
while(t--)
{
    var n = parseInt(readline());
    var str = readline();
    var narr = [];
    var nstr = "";
    var arr = [];
    if(str[0] != 9)
    {
        for(var i = 0; i < n; i++)
        {
            nstr +=(9 - parseInt(str[i]));
        }
        print(nstr);
    }
    else
    {
        for(var i = 0; i < n; i++)
        {
          narr.push(parseInt(str[i]));
        }
        if(narr[n -1] > 1)
        {
            arr.push(11 - narr[n -1]);
        }
        else
        {
            arr.push(1 -  narr[n - 1]);
        }
        for(var i = 1; i < n; i++)
        {
            if((arr[i - 1] + narr[n - i]) > 9)
            {
                if((narr[ n - 1 - i] + 1) > 8)
                {
                    arr.push(18 - (narr[ n - 1 - i] + 1));
                }
                else
                {
                    arr.push(8 - (narr[ n - 1 - i] + 1));
                }
            }
            else
            {
                if((narr[ n - 1 - i] ) > 8)
                {
                    arr.push(18 - (narr[ n - 1 - i] ));
                }
                else
                {
                    arr.push(8 - (narr[ n - 1 - i] ));
                }
            }
        }
        for(var i = n - 1; i > - 1; i--)
        {
            nstr += arr[i];
        }
        print(nstr);
    }
    }

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let n = parseInt(readline());
    let num = parseInt(readline());
    print(Easy(n, num));
  }
}
function Easy(n, number) {
  let first = Math.floor(number / 10 ** (n - 1));
  if (first !== 9) {
    let str = "";
    for (let i = 0; i < n; i++) {
      str += "9";
    }
    return Number(str) - number;
  } else {
    let str = "1";
    for (let i = 0; i < n; i++) {
      str += "1";
    }
    return Number(str) - number;
  }
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let n = parseInt(readline());
    let num = parseInt(readline());
    print(Easy(n, num));
  }
}
function Easy(n, number) {
  let first = Math.floor(number / (10 ** (n - 1)));
  if (first !== 9) {
    let str = "";
    for (let i = 0; i < n; i++) {
      str += "9";
    }
    return Number(str) - number;
  } else {
    let str = "1";
    for (let i = 0; i < n - 1; i++) {
      str += "2";
    }
    str += "1";
    return Number(str) - number;
  }
}

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => lines[i++]
}
const int = (num, radix=10) => parseInt(num, radix)

rl.on('line', line => lines.push(line))

rl.on("close", () => {
  const readLine = createReadLine();
  let t = int(readLine());
  while (t--) {
    const n = int(readLine());
    const num = readLine();
    console.log(f(num, n))
  }
});

function f(num, n) {
  let ans = '';
  if (num[0] == '9') {
    for (let i = 0; i < n - 1; i++) {
      ans += (10 - num[i]) % 10;
    }
    ans += ((11 - num[n - 1]) % 10);
  } else {
    for (let i = 0; i < n; i++) {
      ans += 9 - num[i];
    }
  }
  return ans;
}

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => lines[i++]
}
const int = (num, radix=10) => parseInt(num, radix)

rl.on('line', line => lines.push(line))

rl.on("close", () => {
  const readLine = createReadLine();
  let t = int(readLine());
  while (t--) {
    const n = int(readLine());
    const num = readLine();
    console.log(f(num, n))
  }
});

function f(num, n) {
  let ans = '';
  if (num[0] == '9') {
    for (let i = 0; i < n - 1; i++) {
      ans += 10 - num[i];
    }
    ans += (11 - num[n - 1]);
  } else {
    for (let i = 0; i < n; i++) {
      ans += 9 - num[i]
    }
  }
  return ans;
}

'use strict';

function solve(n, s) {
  if (Number(s[0]) < 9) {
    const res = new Array(n);
    for (let i = n - 1; i >= 0; i--) {
      const num = Number(s[i]);
      res[i] = 9 - num;
    }
    return res.join('');
  } else {
    const res = new Array(n + 1).fill(1);
    for (let i = n - 1; i >= 0; i--) {
      const num = Number(s[i]);
      let dif = res[i + 1] - num;
      if (dif > 0) res[i + 1] = dif;else {
        dif = 10 + dif;
        res[i]--;
        res[i + 1] = dif;
      }
    }
    return res.slice(1).join('');
  }
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const s = await read();
      res[i] = solve(n, s);
    }
    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';

function solve(n, s) {
  const res = new Array(n + 1);
  res[0] = 9;
  for (let i = n - 1; i >= 0; i--) {
    const num = Number(s[i]);
    res[i + 1] = 9 - num;
  }
  return res.join('');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const s = await read();
      res[i] = solve(n, s);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

const checkPalindrome = n=>{
     let str = ""+n;
     for(let i=0;i<Math.floor(str.length/2);i++){
          if(str[i]!==str[str.length-i-1]) return false;
     }
     return true;
}
const solve = (k,n)=>{
     let arr = [10,100,1000,10000,100000,1000000];
     for(let i=arr[k-2];i<arr[k-1];i++){
          if(checkPalindrome(n+i)) return i;
     }
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let k = parseInt(readline());
       let n = parseInt(readline());
       console.log(solve(k,n));
  }
}
main();


A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$).

For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer  — the minimum possible value of $$$k$$$.

NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$.

'use strict';

const rightShift = (i, j) => {
  let hi = 0,
      lo = i & 1073741823;
  if (i > lo) hi = Math.floor(i / 1073741824);else return lo >> j;
  lo >>= j;
  lo |= (hi & (1 << j) - 1) << 30 - j;
  hi >>= j;
  return hi * 1073741824 + lo;
};
const leftShift = (i, j) => {
  let hi = 0,
      lo = i & 1073741823;
  if (i > lo) hi = Math.floor(i / 1073741824);
  hi = hi << j & 1073741823 | lo >> 30 - j;
  lo = lo << j & 1073741823;
  return hi * 1073741824 + lo;
};
let f = [1];
for (let i = 1;; i++) {
  f[i] = f[i - 1] * i;
  f[i] = leftShift(f[i], 10);
  f[i] = rightShift(f[i], 10);
  if (f[i] > 10 ** 12) {
    f.pop();
    break;
  }
}
const cache = Array.from({
  length: f.length
}, () => new Map());
function solve(n) {
  const dfs = (n, r = f.length - 1) => {
    if (r < 0) return Infinity;
    if (cache[r].has(n)) return cache[r].get(n);
    if (n === 0) return 0;
    let res = Infinity;
    let t = n;
    let tmp = 0;
    while (t) {
      if (t & 1) tmp++;
      t = rightShift(t, 1);
    }
    for (let i = r; i >= 0; i--) {
      if (n < f[i]) continue;
      res = Math.min(res, dfs(n - f[i], i - 1) + 1);
    }
    res = Math.min(res, tmp);
    cache[r].set(n, res);
    return res;
  };
  return dfs(n);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    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';

let f = [1];
for (let i = 1;; i++) {
  f[i] = f[i - 1] * i;
  if (f[i] > 10 ** 12) {
    f.pop();
    break;
  }
}
const cache = Array.from({
  length: f.length
}, () => new Map());
function solve(n) {
  const next = (i, j) => {
    let hi = 0,
        lo = i & 1073741823;
    if (i > lo) hi = Math.floor(i / 1073741824);else return lo >> j;
    lo >>= j;
    lo |= (hi & (1 << j) - 1) << 30 - j;
    hi >>= j;
    return hi * 1073741824 + lo;
  };
  const dfs = (n, r = f.length - 1) => {
    if (r < 0) return Infinity;
    if (cache[r].has(n)) return cache[r].get(n);
    if (n === 0) return 0;
    let res = Infinity;
    let t = n;
    let tmp = 0;
    while (t) {
      if (t & 1) tmp++;
      t = next(t, 1);
    }
    for (let i = r; i >= 0; i--) {
      if (n < f[i]) continue;
      res = Math.min(res, dfs(n - f[i], i - 1) + 1);
    }
    res = Math.min(res, tmp);
    cache[r].set(n, res);
    return res;
  };
  return dfs(n);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    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';

let f = [1];
for (let i = 1;; i++) {
  f[i] = f[i - 1] * i;
  if (f[i] > 10 ** 12) {
    f.pop();
    break;
  }
}
const cache = Array.from({
  length: f.length
}, () => new Map());
function solve(n) {
  const next = i => {
    let hi = 0,
        lo = i & 1073741823;
    if (i > lo) hi = Math.floor(i / 1073741824);else return lo >> 1;
    lo >>= 1;
    if (hi & 1) lo |= 536870912;
    hi >>= 1;
    return hi * 1073741824 + lo;
  };
  const dfs = (n, r = f.length - 1) => {
    if (r < 0) return Infinity;
    if (cache[r].has(n)) return cache[r].get(n);
    if (n === 0) return 0;
    let res = Infinity;
    let t = n;
    let tmp = 0;
    while (t) {
      if (t & 1) tmp++;
      t = next(t);
    }
    for (let i = r; i >= 0; i--) {
      if (n < f[i]) continue;
      res = Math.min(res, dfs(n - f[i], i - 1) + 1);
    }
    res = Math.min(res, tmp);
    cache[r].set(n, res);
    return res;
  };
  return dfs(n);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    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';
const { throws } = require('assert');
const { count } = require('console');

 /*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 EPS = 1e-6;
const MOD = 1e9+7;

let powers = [], factorials = [];
const precalc = ()=>{
  let num = 1;
  while (num<1e12){
    powers.push(num);
    num *= 2;
  }
  num = 6;
  for (let i=4; num<1e12; i++){
    factorials.push(num);
    num *= i;
  }
  l({powers, factorials})
};

const calc = (n)=>{
  let bmax = 1<<15;
  let count1 = num=>{
    let s = num.toString(2);
    let cn = 0;
    for (let i=0; i<s.length;i++)if (s[i]=='1')cn++
    return cn;
    let cnt = 0;
    for (let i=0; i<50; i++){
      if ((BigInt(1)<<BigInt(i))&BigInt(num))
        cnt++;
    }
    return cnt;
  }
  let min_res = count1(n);
  l('count n', n, min_res)
  let deduct = (num, bmask)=>{
    for (let i=0; i<14 && num>=0; i++){
      if ((1<<i)&bmask)
        num -= factorials[i];
    }
    return num;
  }
  for (let bmask = 0; bmask<bmax; bmask++){
    let cnum = deduct(n, bmask);
    if (cnum>=0){
      let t = count1(cnum)+count1(bmask);
      if (t<min_res){
        l('update', {n, bmask, cnum, t})
      }
      min_res = Math.min(min_res, t);
    }
  }
  return min_res
};

function main() {
    let T = +readline()
    precalc()
    while (T--){
      let [n] = ra();
      print(calc(n));
    }
}

E.calc = calc;

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

const mxN = 1e12 + 10;

function bitCount (n) {
	cnt = 0;
	for (let i = 0; i < 40; i++) {
		cnt += n & 1;
		n = Math.floor(n/2);
	}
	return cnt;
}

function main () {
	let fact = [1];
	for (let i = 1; fact[i-1] * i <= mxN; i++) {
		fact[i] = fact[i-1] * i;
	}
	fact = fact.slice(3); // 0: 1, 1: 1, 2: 2, 3: 6, 4: 24 => 3: 6, 4: 24,

	let T = rn();
	while (T--) {
		const n = rn();

		let ans = Math.ceil(Math.log2(mxN));
		for (let mask = 0; mask < 1 << fact.length; mask++) {
			let sum = n, k = 0;
			for (let i = 0; i < fact.length; i++) {
				if (mask & (1 << i)) {
					sum -= fact[i];
					k++;
				}
			}
			if (sum >= 0) {
				k += bitCount(sum);
				ans = Math.min(ans, k);
			}
		}

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

const mxN = 1e12 + 10;

function bitCount (n) {
	if (n == 0) return 0;
	return n.toString(2).match(/1/g).length;
}

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

		let fact = [1];
		for (let i = 1; fact[i-1] * i <= mxN; i++) {
			fact[i] = fact[i-1] * i;
		}
		fact = fact.slice(3); // 0:1, 1:1, 2:2, 3:6, 4:24 => 3:6, 4:24,

		let ans = 40;
		for (let mask = 0; mask < 1 << fact.length; mask++) {
			let sum = 0, k = 0;
			for (let i = 0; i < fact.length; i++) {
				if (mask & (1 << i)) {
					sum += fact[i];
					k++;
				}
			}
			if (sum <= n) {
				k += bitCount(n - sum);
				ans = Math.min(ans, k);
			}
		}

		console.log(ans);
	}
}

'use strict';

let f = [1];
for (let i = 1;; i++) {
  f[i] = f[i - 1] * i;
  if (f[i] > 10 ** 12) {
    f.pop();
    break;
  }
}
const cache = Array.from({
  length: f.length
}, () => new Map());
function solve(n) {
  const next = (i, j) => {
    let hi = 0,
        lo = i & 1073741823;
    if (i > lo) hi = Math.floor(i / 1073741824);else return lo >> j;
    lo >>= j;
    lo |= (hi & (1 << j) - 1) << 29 - j;
    hi >>= j;
    return hi * 1073741824 + lo;
  };
  const dfs = (n, r = f.length - 1) => {
    if (r < 0) return Infinity;
    if (cache[r].has(n)) return cache[r].get(n);
    if (n === 0) return 0;
    let res = Infinity;
    let t = n;
    let tmp = 0;
    while (t) {
      if (t & 1) tmp++;
      t = next(t, 1);
    }
    for (let i = r; i >= 0; i--) {
      if (n < f[i]) continue;
      res = Math.min(res, dfs(n - f[i], i - 1) + 1);
    }
    res = Math.min(res, tmp);
    cache[r].set(n, res);
    return res;
  };
  return dfs(n);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    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';

let f = [1];
for (let i = 1;; i++) {
  f[i] = f[i - 1] * i;
  if (f[i] > 10 ** 12) {
    f.pop();
    break;
  }
}
const cache = new Map();
function solve(n) {
  const next = i => {
    let hi = 0,
        lo = i & 1073741823;
    if (i > lo) hi = Math.floor(i / 1073741824);else return lo >> 1;
    lo >>= 1;
    if (hi & 1) lo |= 536870912;
    hi >>= 1;
    return hi * 1073741824 + lo;
  };
  const dfs = (n, r = f.length - 1) => {
    if (cache.has(n)) return cache.get(n);
    if (n === 0) return 0;
    let res = Infinity;
    let t = n;
    let tmp = 0;
    while (t) {
      if (t & 1) tmp++;
      t = next(t);
    }
    for (let i = r; i >= 0; i--) {
      if (n < f[i]) continue;
      res = Math.min(res, dfs(n - f[i], i - 1) + 1);
    }
    res = Math.min(res, tmp);
    cache.set(n, res);
    return res;
  };
  return dfs(n);
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    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';

function solve(n) {
  let nums = [1];
  for (let i = 1;; i++) {
    nums[i] = nums[i - 1] * i;
    if (nums[i] > n) {
      nums.pop();
      break;
    }
  }
  for (let i = 1;; i++) {
    const num = 2 ** i;
    nums.push(num);
    if (num > n) {
      nums.pop();
      break;
    }
  }
  nums = [...new Set(nums)];
  nums.sort((a, b) => a - b);
  let res = 0;
  let r = nums.length - 1;
  while (n) {
    res++;
    let l = 0;
    while (l < r) {
      const m = l + r + 1 >> 1;
      if (nums[m] > n) {
        r = m - 1;
      } else {
        l = m;
      }
    }
    n -= nums[r];
    r--;
  }
  if (n) return -1;
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    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';
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 EPS = 1e-6;
const MOD = 1e9+7;

let powers = [], factorials = [];
const precalc = ()=>{
  let num = 1;
  while (num<1e12){
    powers.push(num);
    num *= 2;
  }
  num = 6;
  for (let i=2; num<1e12; i++){
    factorials.push(num);
    num *= i;
  }
  l({powers, factorials})
};

const calc = (n)=>{
  let bmax = 1<<15;
  let count1 = num=>{
    let cnt = 0;
    for (let i=0; i<50; i++){
      if (BigInt(1<<i)&BigInt(num))
        cnt++;
    }
    return cnt;
  }
  let min_res = count1(n);
  l('count n', n, min_res)
  let deduct = (num, bmask)=>{
    for (let i=0; i<14; i++){
      if (BigInt(1<<i)&BigInt(bmask))
        num -= factorials[i];
    }
    return num;
  }
  for (let bmask = 0; bmask<bmax; bmask++){
    let cnum = deduct(n, bmask);
    if (cnum>=0){
      let t = count1(cnum)+count1(bmask);
      if (t<min_res){
        l('update', {n, bmask, cnum, t})
      }
      min_res = Math.min(min_res, t);
    }
  }
  return min_res
};

function main() {
    let T = +readline()
    precalc()
    while (T--){
      let [n] = ra();
      print(calc(n));
    }
}

E.calc = calc;

'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 EPS = 1e-6;
const MOD = 1e9+7;

let power_numbers;
const precalc = ()=>{
  let set = new Set();
  let num = 1;
  while (num<1e12){
    set.add(num);
    num *= 2;
  }
  num = 1;
  for (let i=2; num<1e12; i++){
    set.add(num);
    num *= i;
  }
  power_numbers = Array.from(set);
  power_numbers.sort((a, b)=>a-b)
  l(power_numbers)
};

let cache = new Map();
const calc = (n)=>{
  let helper = (n, arr)=>{
    if (n==0)
      return 0;
    let K = n+';'+arr.join(',');
    if (cache.has(K)){
      return cache.get(K)
    }
    let min = Infinity;
    for (let i=arr.length; i>=0; i--){
      if (arr[i]<=n){
        let narr = arr.slice(0, i).concat(arr.slice(i+1));
        min = Math.min(min, 1+helper(n-arr[i], narr))
        if (min<Infinity)
          break;
      }
    }
    cache.set(K, min);
    return min;
  };
  let arr = power_numbers.slice(0);
  let r = helper(n, arr)
  if (!Number.isFinite(r))
    return -1;
  return r;
};

function main() {
    let T = +readline()
    precalc()
    while (T--){
      let [n] = ra();
      print(calc(n));
    }
}

E.calc = calc;

'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 EPS = 1e-6;
const MOD = 1e9+7;

let power_numbers;
const precalc = ()=>{
  let set = new Set();
  let num = 1;
  while (num<1e12){
    set.add(num);
    num *= 2;
  }
  num = 1;
  for (let i=2; num<1e12; i++){
    set.add(num);
    num *= i;
  }
  power_numbers = Array.from(set);
  power_numbers.sort((a, b)=>a-b)
};

let cache = new Map();
const calc = (n)=>{
  let helper = (n, arr)=>{
    if (n==0)
      return 0;
    let K = n+';'+arr.join(',');
    if (cache.has(K)){
      return cache.get(K)
    }
    let min = Infinity;
    for (let i=arr.length; i>=0; i--){
      if (arr[i]<=n){
        let narr = arr.slice(0, i).concat(arr.slice(i+1));
        min = Math.min(min, 1+helper(n-arr[i], narr))
        if (min<Infinity)
          break;
      }
    }
    cache.set(K, min);
    return min;
  };
  let arr = power_numbers.slice(0);
  return helper(n, arr)
  return -1;
};

function main() {
    let T = +readline()
    precalc()
    while (T--){
      let [n] = ra();
      print(calc(n));
    }
}

E.calc = calc;


Polycarp was recently given a set of $$$n$$$ (number $$$n$$$ — even) dominoes. Each domino contains two integers from $$$1$$$ to $$$n$$$.Can he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets.For example, if he has $$$4$$$ dominoes: $$$\{1, 4\}$$$, $$$\{1, 3\}$$$, $$$\{3, 2\}$$$ and $$$\{4, 2\}$$$, then Polycarp will be able to divide them into two sets in the required way. The first set can include the first and third dominoes ($$$\{1, 4\}$$$ and $$$\{3, 2\}$$$), and the second set — the second and fourth ones ($$$\{1, 3\}$$$ and $$$\{4, 2\}$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of dominoes. The next $$$n$$$ lines contain pairs of numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) describing the numbers on the $$$i$$$-th domino. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print:   YES, if it is possible to divide $$$n$$$ dominoes into two sets so that the numbers on the dominoes of each set are different;  NO if this is not possible.  You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).

NoteIn the first test case, the dominoes can be divided as follows:   First set of dominoes: $$$[\{1, 2\}, \{4, 3\}]$$$  Second set of dominoes: $$$[\{2, 1\}, \{3, 4\}]$$$  In other words, in the first set we take dominoes with numbers $$$1$$$ and $$$2$$$, and in the second set we take dominoes with numbers $$$3$$$ and $$$4$$$.In the second test case, there's no way to divide dominoes into $$$2$$$ sets, at least one of them will contain repeated number.

const readline = require('readline')

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

function solve(n, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const [a, b] = arr[i]
        if (a === b) return 'NO'
        map[a] = map[a] || []
        map[a].push(i)
        map[b] = map[b] || []
        map[b].push(i)
    }
    const adj = {}
    for (let i = 0; i < arr.length; i++) {
        const [a, b] = arr[i]
        if (map[a].length > 2 || map[b].length > 2) return 'NO'
        map[a].forEach(j => {
            if (i === j) return
            adj[i] = adj[i] || []
            adj[i].push(j)
            adj[j] = adj[j] || []
            adj[j].push(i)
        })
        map[b].forEach(j => {
            if (i === j) return
            adj[i] = adj[i] || []
            adj[i].push(j)
            adj[j] = adj[j] || []
            adj[j].push(i)
        })
    }
    return bipartite(adj, n)[0] ? 'YES' : 'NO'
}
function bipartite(adj, n) {
    let bip = true;
    const s = [];

    for (let i = 0; i < n; i++) {
        s[i] = -1;
    }

    for (let i = 0; i < n; i++){
        if (s[i] != -1) continue;

        s[i] = 0;
        bip &= dfs(adj, i, s)
        if (!bip) return [bip, s]
    }
    return [bip, s];
}
function dfs(adj, r, s) {
    const stack = [[r, 0]]
    while (stack.length) {
        const [u, i] = stack[stack.length - 1]

        const nb = adj[u] || []
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (s[v] == -1){
                s[v] = s[u] ^ 1;
                stack.push([v, 0]);
            } else if (s[u] === s[v]){
                return false
            }
        } else {
            stack.pop()
        }
    }
    return true
}

'use strict';

function solve(n, a) {
  a = a.map(arr => arr.map(num => num - 1));
  {
    const cnt = new Array(n).fill(0);
    for (let [i, j] of a) {
      if (i === j) return 'NO';
      cnt[i]++;
      cnt[j]++;
    }
    for (let i = 0; i < n; i++) {
      if (cnt[i] !== 2) return 'NO';
    }
  }
  const h = new Array(n).fill(-1),
        e = [],
        ne = [];
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, ne[idx] = h[i], h[i] = idx++;
  };
  const map = Array.from({
    length: n
  }, () => []);
  for (let [i, [x, y]] of a.entries()) {
    map[x].push(i);
    map[y].push(i);
  }
  const uf = new UnionFind(n);
  for (let [i, j] of map) {
    add(i, j);
    add(j, i);
    uf.union(i, j);
  }
  let queue = [],
      vis = new Array(n);
  for (let i = 0; i < n; i++) {
    const root = uf.find(i);
    if (vis[root]) continue;
    vis[root] = 1;
    queue.push([root, 0]);
  }
  const res = [];
  vis = new Array(n);
  for (let [u, d] of queue) {
    vis[u] = 1;
    if (d === 0) res.push(u);
    for (let i = h[u]; ~i; i = ne[i]) {
      const v = e[i];
      if (vis[v]) continue;
      vis[v] = 1;
      queue.push([v, d ^ 1]);
    }
  }
  const check = indexs => {
    const vis = new Array(n);
    for (let u of indexs) {
      const [i, j] = a[u];
      if (vis[i] || vis[j]) return false;
      vis[i] = 1;
      vis[j] = 1;
    }
    return true;
  };
  if (res.length === n / 2 && check(res)) {
    return 'YES';
  } else {
    return 'NO';
  }
}
class UnionFind {
  constructor(n) {
    this.p = [...new Array(n).keys()];
    this.find = this.find.bind(this);
    this.union = this.union.bind(this);
    this.isConnect = this.isConnect.bind(this);
  }
  find(i) {
    const {
      p
    } = this;
    while (p[i] !== i) {
      p[i] = p[p[i]];
      i = p[i];
    }
    return p[i];
  }
  union(i, j) {
    const {
      p,
      find
    } = this;
    const ri = find(i),
          rj = find(j);
    if (ri !== rj) p[rj] = ri;
  }
  isConnect(i, j) {
    const {
      find
    } = this;
    const ri = find(i),
          rj = find(j);
    return ri === rj;
  }
}

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

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


There's a chessboard of size $$$n \times n$$$. $$$m$$$ rooks are placed on it in such a way that:   no two rooks occupy the same cell;  no two rooks attack each other. A rook attacks all cells that are in its row or column.Is it possible to move exactly one rook (you can choose which one to move) into a different cell so that no two rooks still attack each other? A rook can move into any cell in its row or column if no other rook stands on its path.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 8$$$) — the size of the chessboard and the number of the rooks. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — the position of the $$$i$$$-th rook: $$$x_i$$$ is the row and $$$y_i$$$ is the column. No two rooks occupy the same cell. No two rooks attack each other.

For each testcase, print "YES" if it's possible to move exactly one rook into a different cell so that no two rooks still attack each other. Otherwise, print "NO".

NoteIn the first testcase, the rooks are in the opposite corners of a $$$2 \times 2$$$ board. Each of them has a move into a neighbouring corner, but moving there means getting attacked by another rook.In the second testcase, there's a single rook in a middle of a $$$3 \times 3$$$ board. It has $$$4$$$ valid moves, and every move is fine because there's no other rook to attack it.

var t = readline();
    for(var i = 0 ; i < t ; ++i){
        inputs = readline().split(' ') ,
        n = inputs[0] , m = inputs[1] , positions = [];
        for(var j = 0 ; j < m ; ++j){
            var rookPosition = readline().split(' ');
        }
        n > m ? print("YES") : print("NO");
    }

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var input = readline().split(' ');
    var c = Number(input[0]); // chessboard size
    var r = Number(input[1]); // num of rooks

    var ansCond = c > r;
    for(; r > 0; r--) {
        readline();
    }

    print(ansCond ? 'YES' : 'NO');
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    let arr = [];
    for (let i = 0; i < n; i++) arr.push(new Array(n).fill(0));
    for (let i = 0; i < m; i++) {
      let [r, c] = iInpArr();
      arr[r - 1][c - 1] = 1;
    }
    if(n===1){
         console.log("NO");
         continue;
    }
    const helper = (r, c) => {
      let j = 0;
      for (let j = 0; j < n; j++) {
        if (arr[j][c] === 1) return false;
      }
      return true;
    };
    let ans;
    for (let i = 0; i < n; i++) {
      ans = false;
      for (let j = 0; j < n; j++) {
        if (arr[i][j] === 1) {
          if (j === 0) ans = helper(i, j + 1);
          else if (j === n - 1) ans = helper(i, j - 1);
          else {
            ans = helper(i, j + 1) || helper(i, j - 1);
          }
        }
      }
      if (ans === true) {
        console.log("YES");
        break;
      }
    }
    if (ans === false) console.log("NO");
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function evaluateBoard(board)
{
    for(let i=0;i<board.length;i++)
    {
       for(let j=0;j<board.length;j++)
        {
            if(board[i][j]==1)
            {
                for(let m=0;m<board.length;m++)
                {
                    if(i!=m)
                    {
                        //console.log("m" + m)
                        //console.log("j" + j)
                        //console.log("i" + i)
                        if(board[m][j]==1)
                            {

                                return false
                            }
                    }
                }
                for(let n=0;n<board.length;n++)
                    {
                        if(j!=n)
                            if(board[i][n]==1)
                                {
                                    return false
                                }

                    }
            }
        }
    }
    return true
}

function main() {

    let t = parseInt(readLine());

    while(t--)
    {
        //const n = parseInt(readLine());

        let nums = readLine().split(" ").map(x=>parseInt(x));
        let n = nums[0]
        let m = nums[1]

        var board = Array(n)
        for(let a=0;a<n;a++)
        {
            board[a] = Array(n)
        }
        //console.log("length" + board.length)
        for(let i=0; i<n;i++)
        {
            for(let j=0; j<n;j++)
            {
                board[i][j] = 0
            }
        }
        for(let i=0; i<m;i++)
        {
            const xy = readLine().split(" ").map(x=>parseInt(x));
            let x= xy[0]-1
            let y= xy[1]-1
            board[x][y] = 1
        }

        var nextCase = false
        //console.log("board" + board)
        for(let i=0; i<n;i++)
        {
            nextCase=false
            for(let j=0; j<n;j++)
            {
                if(board[i][j] == 1)
                {
                    //console.log("i" + i)
                    //console.log("j" + j)

                    let board_new = JSON.parse(JSON.stringify(board))
                    board_new[i][j] = 0

                    //console.log("board1 " + board)
                    //console.log("board_new1 " + board_new)

                    for(let l=0; l<n;l++)
                    {
                        if((l!=i)&&(board_new[l][j]!=1))
                        {
                            let board_new_new = JSON.parse(JSON.stringify(board_new))
                            board_new_new[l][j] = 1
                            //console.log("board_new2 " + board_new_new)
                            if(evaluateBoard(board_new_new))
                            {
                                console.log("YES")
                                nextCase=true;
                                break;
                            }
                        }

                    }
                    if(nextCase)
                    {
                        break;
                    }
                    for(let m=0; m<n;m++)
                    {
                        if((m!=j)&&(board_new[i][m]!=1))
                        {
                            let board_new_new = JSON.parse(JSON.stringify(board_new))
                            board_new_new[i][m] = 1
                            if(evaluateBoard(board_new_new))
                            {
                                console.log("YES")
                                nextCase=true;
                                break;
                            }
                        }

                    }
                }
            }
            if(nextCase)
                break;
        }
        if(nextCase)
            continue;
        console.log("NO")

    }
}

const fs = require("fs");

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

const testCases = [];
let T;

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

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

function solution(testCase) {
  const { n, m, x, y } = testCase;

  let result = m < n ? "YES" : "NO";
  console.log(result);
}

parseInput();

testCases.forEach(solution);

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

// your code goes here

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

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

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

function start(){
	const T = parseInt(lines[0])
	let line = 1
	for(let t = 1; t <= T; t++) {
	    const n = parseInt(lines[line].trim().split(' ')[0], 10)
	    const m = parseInt(lines[line++].trim().split(' ')[1], 10)
	    for(let i = 0; i < m; i++) {
	        line++
	    }
	    console.log(m >= n ? "NO" : "YES")
	}
}

/*
* auther yeling
*
*
*/
'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, m, grid) {
    //print(`${n} ${m} ${grid.join(' ')}`);
    let rows = new Array(n).fill(0);
    let cols = new Array(n).fill(0);
    for(let i = 0; i < grid.length; i++) {
        rows[grid[i][0] - 1]++;
        cols[grid[i][1] - 1]++;
    }
    //zero one two
    let rowRes = [0,0,0];
    let colRes = [0,0,0];

    for(let i = 0; i < n; i++) {
        if(rows[i] <= 2) {
            rowRes[rows[i]]++;
        } else {
            print("NO");
            return;
        }
        if(cols[i] <= 2) {
            colRes[cols[i]]++;
        } else {
            print("NO");
            return;
        }
    }
    if(colRes[2] + rowRes[2] > 1) {
        print("NO");
        return;
    }
    if(colRes[2] == 1 && colRes[0] == 0) {
        print("NO");
        return;
    }
    if(rowRes[2] == 1 && rowRes[0] == 0) {
        print("NO");
        return;
    }
    if(rowRes[1] == n || colRes[1] == n) {
        print("NO");
        return;
    }
    print("YES");
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = readline().trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        let m = n[1];
        let grid = [];
        for(let i = 0; i < m; i++) {
            var x = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
            grid.push(x);
        }
        begin(n[0], m, grid);
    }
}

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

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

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        // const n = +readLine();
        const n_m = readLine().split(' ').map(p => +p);
        let arr = new Array(n_m[1]);
        for(let j = 0; j < n_m[1]; j++){
            arr[j] = readLine().split(' ').map(p => +p);
        }
        let result = myFunc(n_m[0], n_m[1], arr);
        console.log(result);
    }
}

function myFunc(n, m, arr){

    let mapL = new Set();
    let mapC = new Set();

    for(let i = 0; i < m; i++){
        mapL.add(arr[i][0]);
        mapC.add(arr[i][1]);
    }

    if(mapL.size < n || mapC.size < n) return 'YES';

    return 'NO';

}

/*
** Template
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let nm = readline().split(' ').map( Number )
        let n = nm[0], m = nm[1]
        let pos = []
        while(m--) {
            pos.push( readline().split(' ').map( Number ) )
        }
        // let res = readline()
        // console.log( res, solve( nm, pos) )
        console.log( solve( nm, pos) )
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = ( nm, pos ) => {
    let n = nm[0], m = nm[1]

    return ( n > m ) ? 'YES' : 'NO'
}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, m] = rns(),
        a = [];
  for (let i = 0; i < m; i++) a[i] = rns().map(num => num - 1);
  const check = a => {
    const r = [],
          c = [];
    for (let [i, j] of a) {
      if (r[i] || c[j]) return false;
      r[i] = 1;
      c[j] = 1;
    }
    return true;
  };
  for (let [i, [r, c]] of a.entries()) {
    for (let x = 0; x < n; x++) {
      for (let y = 0; y < n; y++) {
        if (x === r && c === y) continue;
        a[i] = [x, y];
        if (check(a)) return 'YES';
      }
    }
    a[i] = [r, c];
  }
  return 'NO';
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

var t = readline();
    for(var i = 0 ; i < t ; ++i){
        inputs = readline().split(' ') ,
        n = inputs[0] , m = inputs[1] , positions = [];
        for(var j = 0 ; j < m ; ++j){
            var rookPosition = readline().split(' ');
            positions.push(...rookPosition);
        }
        positions = [...new Set(positions)];
        positions.length < n ? print("YES") : print("NO");
    }

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    let arr = [];
    for (let i = 0; i < n; i++) arr.push(new Array(n).fill(0));
    for (let i = 0; i < m; i++) {
      let [r, c] = iInpArr();
      arr[r - 1][c - 1] = 1;
    }
    const helper = (r, c) => {
      let j = 0;
      for (let j = 0; j < n; j++) {
        if (arr[j][c] === 1) return false;
      }
      return true;
    };
    let ans;
    for (let i = 0; i < n; i++) {
      ans = false;
      for (let j = 0; j < n; j++) {
        if (arr[i][j] === 1) {
          if (j === 0) ans = helper(i, j + 1);
          else if (j === n - 1) ans = helper(i, j - 1);
          else {
            ans = helper(i, j + 1) || helper(i, j - 1);
          }
        }
      }
      if (ans === true) {
        console.log("YES");
        break;
      }
    }
    if (ans === false) console.log("NO");
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function evaluateBoard(board)
{
    for(let i=0;i<board.length;i++)
    {
       for(let j=0;j<board.length;j++)
        {
            if(board[i][j]==1)
            {
                for(let m=0;m<board.length;m++)
                {
                    if(i!=m)
                    {
                        //console.log("m" + m)
                        //console.log("j" + j)
                        //console.log("i" + i)
                        if(board[m][j]==1)
                            {

                                return false
                            }
                    }
                }
                for(let n=0;n<board.length;n++)
                    {
                        if(j!=n)
                            if(board[i][n]==1)
                                {
                                    return false
                                }

                    }
            }
        }
    }
    return true
}

function main() {

    let t = parseInt(readLine());

    while(t--)
    {
        //const n = parseInt(readLine());

        let nums = readLine().split(" ").map(x=>parseInt(x));
        let n = nums[0]
        let m = nums[1]

        var board = Array(n)
        for(let a=0;a<n;a++)
        {
            board[a] = Array(n)
        }
        //console.log("length" + board.length)
        for(let i=0; i<n;i++)
        {
            for(let j=0; j<n;j++)
            {
                board[i][j] = 0
            }
        }
        for(let i=0; i<m;i++)
        {
            const xy = readLine().split(" ").map(x=>parseInt(x));
            let x= xy[0]-1
            let y= xy[1]-1
            board[x][y] = 1
        }

        var nextCase = false
        //console.log("board" + board)
        for(let i=0; i<n;i++)
        {
            for(let j=0; j<n;j++)
            {
                if(board[i][j] == 1)
                {
                    //console.log("i" + i)
                    //console.log("j" + j)

                    let board_new = JSON.parse(JSON.stringify(board))
                    board_new[i][j] = 0

                    //console.log("board1 " + board)
                    //console.log("board_new1 " + board_new)

                    for(let l=0; l<n;l++)
                    {
                        if(l!=i)
                        {
                            board_new[l][j] = 1
                            //console.log("board_new2 " + board_new)
                            if(evaluateBoard(board_new))
                            {
                                console.log("YES")
                                nextCase=true;
                                break;
                            }
                        }

                    }
                    if(nextCase)
                    {
                        break;
                    }
                    for(let m=0; m<n;m++)
                    {
                        if(m!=j)
                        {
                            board_new[i][m] = 1
                            if(evaluateBoard(board_new))
                            {
                                console.log("YES")
                                nextCase=true;
                                break;
                            }
                        }

                    }
                }
            }
            if(nextCase)
                break;
        }
        if(nextCase)
            continue;
        console.log("NO")

    }
}