Try guessing the statement from this picture:   You are given a non-negative integer $$$d$$$. You have to find two non-negative real numbers $$$a$$$ and $$$b$$$ such that $$$a + b = d$$$ and $$$a \cdot b = d$$$.

The first line contains $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each test case contains one integer $$$d$$$ $$$(0 \le d \le 10^3)$$$.

For each test print one line. If there is an answer for the $$$i$$$-th test, print "Y", and then the numbers $$$a$$$ and $$$b$$$. If there is no answer for the $$$i$$$-th test, print "N". Your answer will be considered correct if $$$|(a + b) - a \cdot b| \le 10^{-6}$$$ and $$$|(a + b) - d| \le 10^{-6}$$$.

var num = parseInt(readline());
for (var i = 0; i < num; i++) {
	var curNum = parseInt(readline());
	var d = curNum * curNum - 4 * curNum;
	if ( d < 0 ) {
		print('N');
    } else if ( d === 0 ) {
		print('Y ' + curNum / 2 + ' ' + curNum / 2);
    } else {
		d = Math.sqrt(d);
		print('Y ' + (curNum+d)/2 + ' ' + (curNum-d)/2);
    }
}

function solve(n) {
    var a = 0;
    var b = n;

    var min = 1;
    var max = 2;
    var average = 0;

    if (n === 0) {
        print('Y 0 0');
        return;
    }

    while (max - min > 10e-13) {
        average = (min + max) / 2;
        a = n - average;
        b = average;

        if (a * b > n) {
            max = average;
        } else {
            min = average;
        }
    }

    if (Math.abs(a + b - a * b) < 10e-6 && Math.abs(a + b - n) < 10e-6) {
        print('Y ' + a + ' ' + b);
    } else {
        print('N');
    }
}

var lines = +readline();
for(var i = 0; i<lines; i++) {
    solve(+readline())
}

var T = parseInt(readline());
for(var t=1;t<=T;t++)
{
    var d=parseInt(readline());//aici da ReferenceError: readLine is not defined
    if(d*d-4*d<0)
    {
        print("N");
        continue;
    }
    var delta=Math.sqrt(d*d-4*d);
    var t1=(d-delta)/2,t2=(d+delta)/2;
    print('Y',t1,t2);
}

function doIt() {

	var cnt = +readline();
	var res = [];
	var minDiff = Math.pow(10, -6);
	var step = Math.pow(10, -9);

	for(var i = 0; i < cnt; i++) {
		var num = +readline();
		var half = num / 2;
		var diff = Math.pow(half, 2) - num;
		if(diff === 0) {
		    print('Y ' + half + ' ' + half);
		    continue;
		}else if(diff < 0) {
			print('N');
			continue;
		}

		var start = 1;
		var finish = 2;

		while(start < finish) {
			var val1 = ('' + ((start + finish) / 2)).split('.');
         if(val1.length > 1) {
            val1[1] = val1[1].substr(0, 9);
         }
         val1 = +(val1.join('.'));

			var val2 = num - val1;

			diff = val1 * val2 - num;
			if(Math.abs(diff) <= minDiff) {
            val2 = Math.floor(val2 * 1000000000) / 1000000000;
				print('Y ' + val2 + ' ' + val1);
				break;
			}

			if(diff < 0) {
				start = val1 + step;
			} else {
				finish = val1 - step;
			}
		}
	}

}

doIt();

'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 main()
{
	const t=parseInt(readLine());
	for(let k=0;k<t;++k)
	{
		const n=+(readLine());
		// const [a,b,c]=readLine().trim().split(" ").map(x=>{return +(x);});
		let lc=0,lo=0,hi=n/2,mid;
		while(lc<1000)
		{
			mid=(lo+hi)/2;
			if(((n-mid)*mid)>n)
				hi=mid;
			else
				lo=mid;
			lc++;
		}
		if(Math.abs(mid*(n-mid)-n)<=0.000001)
			console.log('Y '+(n-mid)+' '+mid);
		else
			console.log('N');
	}
	return 0;
}

function solve(n) {
    var a = 0;
    var b = n;

    var min = 1;
    var max = 2;
    var average = 0;

    if (n === 0) {
        print('Y 0 0');
        return;
    }

    while (max - min > 10e-9) {
        average = (min + max) / 2;
        a = n - average;
        b = average;

        if (a * b > n) {
            max = average;
        } else {
            min = average;
        }
    }

    if (Math.abs(a + b - a * b) < 10e-6 && Math.abs(a + b - n) < 10e-6) {
        print('Y ' + a + ' ' + b);
    } else {
        print('N');
    }
}

var lines = +readline();
for(var i = 0; i<lines; i++) {
    solve(+readline())
}

function solve(n) {
    var a = 0;
    var b = n;

    var min = 1;
    var max = 2;
    var average = 0;

    if (n === 0) {
        write('Y 0 0');
        return;
    }

    while (max - min > 10e-9) {
        average = (min + max) / 2;
        a = n - average;
        b = average;

        if (a * b > n) {
            max = average;
        } else {
            min = average;
        }
    }

    if (Math.abs(a + b - a * b) < 10e-6 && Math.abs(a + b - n) < 10e-6) {
        write('Y ' + a + ' ' + b);
    } else {
        write('N');
    }
}

var lines = +readline();
for(var i = 0; i<lines; i++) {
    solve(+readline())
}

function doIt() {

	var cnt = +readline();
	var res = [];
	var minDiff = Math.pow(10, -7);
	var step = Math.pow(10, -9);

	for(var i = 0; i < cnt; i++) {
		var num = +readline();
		var half = num / 2;
		var diff = Math.pow(half, 2) - num;
		if(diff === 0) {
		    print('Y ' + half + ' ' + half);
		}else if(diff < 0) {
			print('N');
			continue;
		}

		var start = 1;
		var finish = 2;

		while(start < finish) {
			var val1 = ('' + ((start + finish) / 2)).split('.');
         if(val1.length > 1) {
            val1[1] = val1[1].substr(0, 9);
         }
         val1 = +(val1.join('.'));

			var val2 = num - val1;

			diff = val1 * val2 - num;
			if(Math.abs(diff) <= minDiff) {
            val2 = Math.floor(val2 * 1000000000) / 1000000000;
				print('Y ' + val2 + ' ' + val1);
				break;
			}

			if(diff < 0) {
				start = val1 + step;
			} else {
				finish = val1 - step;
			}
		}
	}

}

doIt();

var cnt = +readline();
	var res = [];
	var minDiff = Math.pow(10, -6);
	var step = Math.pow(10, -9);

	for(var i = 0; i < cnt; i++) {
		var num = +readline();
		var diff = Math.pow(num / 2, 2) - num;
		if(diff < 0) {
			print('N');
			continue;
		}

		var start = 1;
		var finish = 2;

		while(start < finish) {
			var val1 = (start + finish) / 2;
			var val2 = num - val1;

			var diff = val1 * val2 - num;
			if(Math.abs(diff) <= minDiff) {
				print('Y ' + val1 + ' ' + val2);
				break;
			}

			if(diff < 0) {
				start = val1 + step;
			} else {
				finish = val1 - step;
			}
		}
	}

function doIt() {

	var cnt = +readline();
	var res = [];
	var minDiff = Math.pow(10, -7);
	var step = Math.pow(10, -9);

	for(var i = 0; i < cnt; i++) {
		var num = +readline();
		var diff = Math.pow(num / 2, 2) - num;
		if(diff < 0) {
			print('N');
			continue;
		}

		var start = 1;
		var finish = 2;

		while(start < finish) {
			var val1 = ('' + ((start + finish) / 2)).split('.');
         if(val1.length > 1) {
            val1[1] = val1[1].substr(0, 9);
         }
         val1 = +(val1.join('.'));

			var val2 = num - val1;

			diff = val1 * val2 - num;
			if(Math.abs(diff) <= minDiff) {
            val2 = Math.floor(val2 * 1000000000) / 1000000000;
				print('Y ' + val2 + ' ' + val1);
				break;
			}

			if(diff < 0) {
				start = val1 + step;
			} else {
				finish = val1 - step;
			}
		}
	}

}

doIt();

function doIt() {

	var cnt = +readline();
	var res = [];
	var minDiff = Math.pow(10, -7);
	var step = Math.pow(10, -9);

	for(var i = 0; i < cnt; i++) {
		var num = +readline();
		var half = num / 2;
		var diff = Math.pow(half, 2) - num;
		if(diff === 0) {
		    print('Y ' + half + ' ' + half);
		    continue;
		}else if(diff < 0) {
			print('N');
			continue;
		}

		var start = 1;
		var finish = 2;

		while(start < finish) {
			var val1 = ('' + ((start + finish) / 2)).split('.');
         if(val1.length > 1) {
            val1[1] = val1[1].substr(0, 9);
         }
         val1 = +(val1.join('.'));

			var val2 = num - val1;

			diff = val1 * val2 - num;
			if(Math.abs(diff) <= minDiff) {
            val2 = Math.floor(val2 * 1000000000) / 1000000000;
				print('Y ' + val2 + ' ' + val1);
				break;
			}

			if(diff < 0) {
				start = val1 + step;
			} else {
				finish = val1 - step;
			}
		}
	}

}

doIt();

function doIt() {

	var cnt = +readline();
	var res = [];
	var minDiff = Math.pow(10, -6);
	var step = Math.pow(10, -9);

	for(var i = 0; i < cnt; i++) {
		var num = +readline();
		var diff = Math.pow(num / 2, 2) - num;
		if(diff < 0) {
			print('N');
			continue;
		}

		var start = 1;
		var finish = 2;

		while(start < finish) {
			var val1 = ('' + ((start + finish) / 2)).split('.');
         if(val1.length > 1) {
            val1[1] = val1[1].substr(0, 9);
         }
         val1 = +(val1.join('.'));

			var val2 = num - val1;

			diff = val1 * val2 - num;
			if(Math.abs(diff) <= minDiff) {
				print('Y ' + val1 + ' ' + val2);
				break;
			}

			if(diff < 0) {
				start = val1 + step;
			} else {
				finish = val1 - step;
			}
		}
	}

}

doIt();


Long ago, you thought of two finite arithmetic progressions $$$A$$$ and $$$B$$$. Then you found out another sequence $$$C$$$ containing all elements common to both $$$A$$$ and $$$B$$$. It is not hard to see that $$$C$$$ is also a finite arithmetic progression. After many years, you forgot what $$$A$$$ was but remember $$$B$$$ and $$$C$$$. You are, for some reason, determined to find this lost arithmetic progression. Before you begin this eternal search, you want to know how many different finite arithmetic progressions exist which can be your lost progression $$$A$$$. Two arithmetic progressions are considered different if they differ in their first term, common difference or number of terms.It may be possible that there are infinitely many such progressions, in which case you won't even try to look for them! Print $$$-1$$$ in all such cases. Even if there are finite number of them, the answer might be very large. So, you are only interested to find the answer modulo $$$10^9+7$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) denoting the number of testcases. The first line of each testcase contains three integers $$$b$$$, $$$q$$$ and $$$y$$$ ($$$-10^9\leq b\leq 10^9$$$, $$$1\leq q\leq 10^9$$$, $$$2\leq y\leq 10^9$$$) denoting the first term, common difference and number of terms of $$$B$$$ respectively. The second line of each testcase contains three integers $$$c$$$, $$$r$$$ and $$$z$$$ ($$$-10^9\leq c\leq 10^9$$$, $$$1\leq r\leq 10^9$$$, $$$2\leq z\leq 10^9$$$) denoting the first term, common difference and number of terms of $$$C$$$ respectively.

For each testcase, print a single line containing a single integer. If there are infinitely many finite arithmetic progressions which could be your lost progression $$$A$$$, print $$$-1$$$. Otherwise, print the number of finite arithmetic progressions which could be your lost progression $$$A$$$ modulo $$$10^9+7$$$. In particular, if there are no such finite arithmetic progressions, print $$$0$$$.

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

function solve(sb, sc) {
    const [fb, db, nb] = sb
    const lb = fb + db * (nb - 1n)
    const [fc, dc, nc] = sc
    const lc = fc + dc * (nc - 1n)
    const cprev = fc - dc
    const cnext = lc + dc
    // check c in b
    if (!cal(fc, fb, db, nb) || !cal(lc, fb, db, nb)) return 0
    // check da
    if (dc % db) return 0
    //
    if (!cal(cprev, fb, db, nb) || !cal(cnext, fb, db, nb)) return -1

    let ans = 0
    let must = dc / db
    const fs = getFactors(Number(db))
    for (let i = 0; i < fs.length; i++) {
        const f = BigInt(fs[i])
        const da = must * f
        const g = gcd(da, db)
        if (da / g * db !== dc) continue
        //
        const x = Number(dc / da)
        // ans += x * x
        ans = add(ans, mul(x, x))
// console.log(da, x)
    }
    return ans
}
function getFactors(x) {
    const limit = Math.floor(Math.sqrt(x))
    const ans = []
    for (let i = 1; i <= limit; i++) {
        if (x % i) continue
        if (x / i === i) {
            ans.push(i)
        } else {
            ans.push(i, x / i)
        }
    }
    return ans
}
function cal(x, f, d, n) {
    const r = (x - f) % d
    if (r) return false
    const i = (x - f) / d + 1n
    return i <= n && i >= 1n
}

function gcd(a, b) {
    if (a === 0n) return b
    if (b === 0n) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}

const MOD = 1e9 + 7
const MOD_CUT = ((1 << 20) * (1 << 20)) % MOD
function add(a, b) {
    return (a + b) % MOD
}
function minus(a, b) {
    return add(add(a, -b), MOD)
}
function mul(a, b) {
    let r = (a >> 20) * (b >> 20) * MOD_CUT
        + (a & 0xfff00000) * (b & 0xfffff)
        + (a & 0xfffff) * b
    return r % MOD
}

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

function solve(sb, sc) {
    const [fb, db, nb] = sb
    const lb = fb + db * (nb - 1n)
    const [fc, dc, nc] = sc
    const lc = fc + dc * (nc - 1n)
    const cprev = fc - dc
    const cnext = lc + dc
    // check c in b
    if (!cal(fc, fb, db, nb) || !cal(lc, fb, db, nb)) return 0
    // check da
    if (dc % db) return 0
    //
    if (!cal(cprev, fb, db, nb) || !cal(cnext, fb, db, nb)) return -1

    let ans = 0
    let must = dc / db
    const fs = getFactors(Number(db))
    for (let i = 0; i < fs.length; i++) {
        const f = BigInt(fs[i])
        const da = must * f
        const x = Number(dc / da)
        // ans += x * x
        ans = add(ans, mul(x, x))
// console.log(da, x)
    }
    return ans
}
function getFactors(x) {
    const limit = Math.floor(Math.sqrt(x))
    const ans = []
    for (let i = 1; i <= limit; i++) {
        if (x % i) continue
        if (x / i === i) {
            ans.push(i)
        } else {
            ans.push(i, x / i)
        }
    }
    return ans
}
function cal(x, f, d, n) {
    const r = (x - f) % d
    if (r) return false
    const i = (x - f) / d + 1n
    return i <= n && i >= 1n
}
const MOD = 1e9 + 7
const MOD_CUT = ((1 << 20) * (1 << 20)) % MOD
function add(a, b) {
    return (a + b) % MOD
}
function minus(a, b) {
    return add(add(a, -b), MOD)
}
function mul(a, b) {
    let r = (a >> 20) * (b >> 20) * MOD_CUT
        + (a & 0xfff00000) * (b & 0xfffff)
        + (a & 0xfffff) * b
    return r % MOD
}


You have two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. You would like to make all the elements of both strings equal to $$$0$$$. Unfortunately, you can modify the contents of these strings using only the following operation:  You choose two indices $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$);  For every $$$i$$$ that respects $$$l \le i \le r$$$, change $$$a_i$$$ to the opposite. That is, $$$a_i := 1 - a_i$$$;  For every $$$i$$$ that respects either $$$1 \le i < l$$$ or $$$r < i \le n$$$, change $$$b_i$$$ to the opposite. That is, $$$b_i := 1 - b_i$$$. Your task is to determine if this is possible, and if it is, to find such an appropriate chain of operations. The number of operations should not exceed $$$n + 5$$$. It can be proven that if such chain of operations exists, one exists with at most $$$n + 5$$$ operations.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the strings. The second line of each test case contains a binary string $$$a$$$, consisting only of characters 0 and 1, of length $$$n$$$. The third line of each test case contains a binary string $$$b$$$, consisting only of characters 0 and 1, of length $$$n$$$. It is guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print first "YES" if it's possible to make all the elements of both strings equal to $$$0$$$. Otherwise, print "NO". If the answer is "YES", on the next line print a single integer $$$k$$$ ($$$0 \le k \le n + 5$$$) — the number of operations. Then $$$k$$$ lines follows, each contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the description of the operation. If there are several correct answers, print any of them.

YES
1
2 2
NO
NO
YES
2
1 2
2 2
YES
2
1 1
2 3

NoteIn the first test case, we can perform one operation with $$$l = 2$$$ and $$$r = 2$$$. So $$$a_2 := 1 - 1 = 0$$$ and string $$$a$$$ became equal to 000. $$$b_1 := 1 - 1 = 0$$$, $$$b_3 := 1 - 1 = 0$$$ and string $$$b$$$ became equal to 000.In the second and in the third test cases, it can be proven that it's impossible to make all elements of both strings equal to $$$0$$$.In the fourth test case, we can perform an operation with $$$l = 1$$$ and $$$r = 2$$$, then string $$$a$$$ became equal to 01, and string $$$b$$$ doesn't change. Then we perform an operation with $$$l = 2$$$ and $$$r = 2$$$, then $$$a_2 := 1 - 1 = 0$$$ and $$$b_1 = 1 - 1 = 0$$$. So both of string $$$a$$$ and $$$b$$$ became equal to 00.In the fifth test case, we can perform an operation with $$$l = 1$$$ and $$$r = 1$$$. Then string $$$a$$$ became equal to 011 and string $$$b$$$ became equal to 100. Then we can perform an operation with $$$l = 2$$$ and $$$r = 3$$$, so both of string $$$a$$$ and $$$b$$$ became equal to 000.

function solve() {
    var n = Number(read());
    var a = read();
    var b = read();
    var aOneIndexes = [];
    var equalsCount = 0;
    for (var i = 0; i < n; i++) {
        if (a[i] === b[i]) {
            equalsCount++;
        }
        if (a[i] === '1') {
            aOneIndexes.push(i);
        }
    }
    if (equalsCount !== 0 && equalsCount !== n) {
        write('NO');
        return;
    }
    write('YES');
    var operationsOdd = ((aOneIndexes.length) & 1);
    var equalityOdd = equalsCount === n ? 0 : 1;
    var needAddOperations = !!(operationsOdd ^ equalityOdd);
    write(aOneIndexes.length + (needAddOperations ? 3 : 0));
    for (i = 0; i < aOneIndexes.length; i++) {
        var index = aOneIndexes[i] + 1;
        write(index + ' ' + index);
    }
    if (needAddOperations) {
        write('1 ' + n);
        write('1 1');
        write('2 ' + n);
    }
}

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

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

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

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

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

'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 = rn(),
        a = read(),
        b = read();
  const tr = new SegTree(n);
  const res = [];
  for (let i = 0, j = 0; i < n; i = ++j) {
    if (a[i] === '1') continue;
    while (a[j + 1] === '0') j++;
    res.push([i, j]);
    if (i) tr.update(0, i - 1, 1);
    if (j < n - 1) tr.update(j + 1, n - 1, 1);
  }
  let one = 0,
      zero = 0;
  for (let i = 0; i < n; i++) {
    const x = tr.query(i, i);
    if (x & 1) {
      if (b[i] === '0') one++;else zero++;
    } else {
      if (b[i] === '0') zero++;else one++;
    }
    if (zero && one) return 'No';
  }
  if (zero) res.push([0, n - 1]);else res.push([0, 0], [1, n - 1]);
  return `Yes\n${res.length}\n${res.map(([l, r]) => `${l + 1} ${r + 1}`).join('\n')}`;
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(val = 0, left = null, right = null) {
    return {
      val,
      left,
      right,
      add: 0
    };
  }
  _down(node, l, r) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    const mid = Math.floor((l + r) / 2);
    left.add += node.add;
    left.val += node.add * (mid - l + 1);
    right.add += node.add;
    right.val += node.add * (r - mid);
    node.add = 0;
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.val = left.val + right.val;
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (l === x && r === y) {
      node.add += z;
      node.val += z * (r - l + 1);
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return 0;
    if (!node) return 0;
    if (l === x && r === y) return node.val;
    let res = 0,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else res = this._query(node.left, l, mid, x, mid) + this._query(node.right, mid + 1, r, mid + 1, y);
    this._up(node);
    return res;
  }
}
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++) {
      let s = solve(r);
      if (s === undefined) s = '';
      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);
}();


Find the minimum area of a square land on which you can place two identical rectangular $$$a \times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally,   You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 100$$$) — positive integers (you are given just the sizes, but not their positions).  Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.    The picture shows a square that contains red and green rectangles.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) —the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — side lengths of the rectangles.

Print $$$t$$$ answers to the test cases. Each answer must be a single integer — minimal area of square land, that contains two rectangles with dimensions $$$a \times b$$$.

NoteBelow are the answers for the first two test cases:

var testCase = parseInt(readline());

for(var tc = 0; tc < testCase; tc++){
    var input = readline().split(" ").map((val) => parseInt(val));
    var a1 = input[0];
    var b1 = input[1];
    var minSize = Math.min(a1, b1);
    var maxSize = Math.max(a1, b1);

    var size = (maxSize > 2*minSize ? maxSize : 2*minSize);
    print(size * size);
}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var ab = readline()
    .split(" ")
    .map((val) => parseInt(val));
  var a = ab[0];
  var b = ab[1];
  if (a == b) {
    print(a * 2 * (a * 2));
  } else {
    var min = Math.min(a, b);
    var max = Math.max(a, b);
    if (min * 2 >= max) print(Math.pow(min * 2, 2));
    else print(Math.pow(max, 2));
  }
}

var n = parseInt(readline());
while(n--)
{
    var i = readline().split(" ").map(x => parseInt(x));
    var max = Math.max(i[0], i[1]);
    var min = Math.min(i[0], i[1]);
    var ans = Math.max(2*min, max);
    print(ans*ans);
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var ab = readNumArray();
    var a = ab[0];
    var b = ab[1];
    var abMin = a < b ? a : b;
    var abMax = a > b ? a : b;
    var maxxx = abMin * 2 > abMax ? abMin * 2 : abMax;

    print(maxxx * maxxx);
  }
}

main();

function solve() {
    var data = readIntArray();
    var a = data[0]
    var b = data[1]

    var min = Math.min(a,b)
    var max = Math.max(a,b)

    var min2 = min * 2
    print(min*2 < max ? max * max : min2 * min2)
}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

var t = parseInt(readline());

while(t--){
  var input = readline().split(" ").map(function(x) { return parseInt(x); });
  var a = input[0]
  var b = input[1]

  var max = Math.max(a, b)
  var min = Math.min(a, b)

  var result = 0;
  if (max > 2 * min)
  {
    result = max * max;
  }
  else
  {
    result = (2 * min) * (2 * min)
  }

  print(result);
}

var numOfInput = parseInt(readline());
while(numOfInput--)
{
    var input = readline().split(" ").map(x => parseInt(x));
    var max = Math.max(input[0], input[1]);
    var min = Math.min(input[0], input[1]);
    print((2 * min) > max ? (4 * min * min) : (max * max));
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var aRib = rectangleRibs[0];
    var bRib = rectangleRibs[1];

    var rib = Math.min(Math.max(aRib * 2, bRib), Math.max(aRib, bRib * 2));
    print(rib * rib);
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline()
        .split(" ")
        .map(number => parseInt(number));

    var side = Math.min(...rectangleRibs) * 2;
    var maxRib = Math.max(...rectangleRibs);

    if (side >= maxRib)
        print(side * side);
    else
        print(maxRib * maxRib);
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var minRib = parseInt(rectangleRibs[0]);
    var maxRib = parseInt(rectangleRibs[1]);
    if (maxRib < minRib) {
        minRib = rectangleRibs[1];
        maxRib = rectangleRibs[0];
    }

    var side = minRib * 2;
    if (side >= maxRib)
        print(side * side);
    else
        print(maxRib * maxRib);
}

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

input.question('line', data => {
	let n = Number(data);
	input.on('line', (data)=> {
		let line =  data.split(' ');
		let a = Number(line[0]);
		let b = Number(line[1]);
		let L = Math.max(a, b);
		let l = Math.min(a, b);
		l *= 2;
		L = Math.max(L, l);
		console.log(L**2);
	});
});

var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var a = one[0];
		var b = one[1];
		var min = Math.min(a,b);
		var max = Math.max(a,b);
		if(min * 2 > max){
			output[i] = Math.pow(min * 2, 2);
		}else{
			output[i] = Math.pow(max, 2);
		}
	}
	myout(myconv(output,9));
}

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

let input = [];

rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solve(input);
  process.exit();
});

function solve(input) {
  const t = input[0];

  for (let x = 1; x <= t; x++) {
    const [n1, n2] = input[x].split(" ").map((num) => Number(num));

    //작은 쪽을 a라 해야 한다.
    const a = n1 > n2 ? n2 : n1;
    const b = n1 > n2 ? n1 : n2;

    //1. 적당한 직사각형일 때
    if (2 * a >= b) {
      console.log(2 * a * 2 * a);
    }
    //2. 한 쪽이 매우 긴 직사각형일 때
    else {
      console.log(b * b);
    }
  }
}

/*
  Q. 최소 정사각형의 넓이 구하라. 2개의 똑같은 a*b의 직사각형을 놓을 수 있는

  1. 주어진 사각형들을 모두 포함하는 최소 공간의 크기를 구하라
  2. 회전 가능 (단, 변이 항상 수평)
  3. 이동 가능
  4. 겹치기 불가능
*/

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

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

  const [a, b] = d.split(' ').map(Number);
  // const v1 = Math.min(a, b) * 2;
  // const v2 = Math.max(a, b);

  // const ans = v1 >= a && v1 >= b ? v1 ** 2 : v2 ** 2;

  const ans = Math.min(Math.max(a*2, b), Math.max(a, b*2))**2;
  console.log(ans);

  c++;
});

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

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

  const [a, b] = d.split(' ').map(Number);
  const v1 = Math.min(a, b) * 2;
  const v2 = Math.max(a, b);

  const ans = v1 >= a && v1 >= b ? v1 ** 2 : v2 ** 2;

  console.log(ans);

  c++;
});

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const [a, b] = lines[i+1].split(' ').map(x => +x)
    let l = Math.min(a, b) * 2
    if (l < Math.max(a, b)) {
      l = Math.max(a, b)
    }
    console.log(l * l)
  }
}

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

'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 main() {
    var num = parseInt(readLine());

    for (var i = 0; i < num; i++) {
        var rectangleRibs = readLine().split(" ");

        var minRib = parseInt(rectangleRibs[0]);
        var maxRib = parseInt(rectangleRibs[1]);
        if (maxRib < minRib) {
            minRib = rectangleRibs[1];
            maxRib = rectangleRibs[0];
        }

        var side = minRib * 2;
        if (side >= maxRib)
            console.log(side * side);
        else
            console.log(maxRib * maxRib);
    }
}

// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

/**
 *
 * @param {*} str
 * @param {*} seperator
 */
function splitter(str, seperator = '') {
    return str.trim().split(seperator);
}

/**
 *
 * @param {*} arr
 */
function strToNumArr(arr = []) {
    return arr.map(num => Number(num));
}

/**
 *
 * @param {*} num1
 * @param {*} num2
 */
function matrixArray(num1, num2) {
    return Array(num1).fill(Array(num2));
}

let log = function () {
    return Function.prototype.bind.call(console.log, console, '');
}();

function removeEmptyItem(arr, index) {
    return arr.slice(0, index).concat(arr.slice(index + 1, arr.length));
}

function range(min, max) {

    let arr = [];
    for (let index = min; index < max; index++) {
        arr.push(index);

    }
    return arr;
}

function main(input) {
    let output = nameLookUp(input);
    //process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let t = +inputs[0].trim();

    for (let index = 1; index <= t; index++) {
        const element = strToNumArr(inputs[index].trim().split(' '));

        let side = Math.min(Math.max(2 * element[0], element[1]), Math.max(2 * element[1], element[0]));
        console.log(side * side);
    }
}

'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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {

    let cases = parseInt(readline(), 10);
    for (var X = 0; X < cases; X++) {
      let [a, b] = readline().split(" ").map(e => parseInt(e));
      const {pow, max, min} = Math;

      const c = pow(min(a,b) * 2, 2);
      const s = pow(max(a,b), 2);
      console.log(Math.max(c, s));
      //break;
      //console.log(Math.pow(Math.max(a,b) + Math.max(a,b) , 2))
    }

}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var minRib = rectangleRibs[0];
    var maxRib = rectangleRibs[1];
    if (rectangleRibs[1] < rectangleRibs[0]) {
        minRib = rectangleRibs[1];
        maxRib = rectangleRibs[0];
    }

    if (minRib * 2 >= maxRib)
        print(minRib * minRib);
    else
        print(maxRib * maxRib);
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var minRib = rectangleRibs[0];
    var maxRib = rectangleRibs[1];
    if (maxRib < minRib) {
        minRib = rectangleRibs[1];
        maxRib = rectangleRibs[0];
    }

    if (minRib * 2 > maxRib)
        print(minRib * minRib * 4);
    if (maxRib == minRib)
        print(maxRib * maxRib);
    else
        print(maxRib * maxRib);
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var minRib = rectangleRibs[0];
    var maxRib = rectangleRibs[1];
    if (maxRib < minRib) {
        minRib = rectangleRibs[1];
        maxRib = rectangleRibs[0];
    }

    var side = minRib * 2;
    if (side >= maxRib)
        print(side * side);
    else
        print(maxRib * maxRib);
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var minRib = rectangleRibs[0];
    var maxRib = rectangleRibs[1];
    if (rectangleRibs[1] < rectangleRibs[0]) {
        minRib = rectangleRibs[1];
        maxRib = rectangleRibs[0];
    }

    if (minRib * 2 >= maxRib)
        print(minRib * minRib * 2);
    else
        print(maxRib * maxRib);
}

var num = parseInt(readline());

for (var i = 0; i < num; i++) {
    var rectangleRibs = readline().split(" ");

    var minRib = rectangleRibs[0];
    var maxRib = rectangleRibs[1];
    if (rectangleRibs[1] < rectangleRibs[0]) {
        minRib = rectangleRibs[1];
        maxRib = rectangleRibs[0];
    }

    if (minRib * 2 >= maxRib)
        print(minRib * minRib * 4);
    else
        print(maxRib * maxRib);
}

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

let input = [];

rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solve(input);
  process.exit();
});

function solve(input) {
  const t = input[0];

  for (let x = 1; x <= t; x++) {
    const [n1, n2] = input[x].split(" ");

    //작은 쪽을 a라 해야 한다.
    const a = n1 > n2 ? n2 : n1;
    const b = n1 > n2 ? n1 : n2;

    //1. 정사각형일 때
    if (a === b) {
      console.log(4 * a * a);
    }
    //2. 적당한 직사각형일 때
    else if (2 * a >= b) {
      console.log(2 * a * 2 * a);
    }
    //3. 한 쪽이 매우 긴 직사각형일 때
    else {
      console.log(b * b);
    }
  }
}

/*
  Q. 최소 정사각형의 넓이 구하라. 2개의 똑같은 a*b의 직사각형을 놓을 수 있는

  1. 주어진 사각형들을 모두 포함하는 최소 공간의 크기를 구하라
  2. 회전 가능 (단, 변이 항상 수평)
  3. 이동 가능
  4. 겹치기 불가능
*/

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

let input = [];

rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  solve(input);
  process.exit();
});

function solve(input) {
  const t = input[0];

  for (let x = 1; x <= t; x++) {
    const [n1, n2] = input[x].split(" ");

    //작은 쪽을 a라 해야 한다.
    const a = n1 > n2 ? n2 : n1;
    const b = n1 > n2 ? n1 : n2;

    //1. 적당한 직사각형일 때
    if (2 * a >= b) {
      console.log(2 * a * 2 * a);
    }
    //2. 한 쪽이 매우 긴 직사각형일 때
    else {
      console.log(b * b);
    }
  }
}

/*
  Q. 최소 정사각형의 넓이 구하라. 2개의 똑같은 a*b의 직사각형을 놓을 수 있는

  1. 주어진 사각형들을 모두 포함하는 최소 공간의 크기를 구하라
  2. 회전 가능 (단, 변이 항상 수평)
  3. 이동 가능
  4. 겹치기 불가능
*/


On a circle lie $$$2n$$$ distinct points, with the following property: however you choose $$$3$$$ chords that connect $$$3$$$ disjoint pairs of points, no point strictly inside the circle belongs to all $$$3$$$ chords. The points are numbered $$$1, \, 2, \, \dots, \, 2n$$$ in clockwise order.Initially, $$$k$$$ chords connect $$$k$$$ pairs of points, in such a way that all the $$$2k$$$ endpoints of these chords are distinct.You want to draw $$$n - k$$$ additional chords that connect the remaining $$$2(n - k)$$$ points (each point must be an endpoint of exactly one chord).In the end, let $$$x$$$ be the total number of intersections among all $$$n$$$ chords. Compute the maximum value that $$$x$$$ can attain if you choose the $$$n - k$$$ chords optimally.Note that the exact position of the $$$2n$$$ points is not relevant, as long as the property stated in the first paragraph holds.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le n$$$) — half the number of points and the number of chords initially drawn. Then $$$k$$$ lines follow. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, \, y_i \le 2n$$$, $$$x_i \ne y_i$$$) — the endpoints of the $$$i$$$-th chord. It is guaranteed that the $$$2k$$$ numbers $$$x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k$$$ are all distinct.

For each test case, output the maximum number of intersections that can be obtained by drawing $$$n - k$$$ additional chords.

NoteIn the first test case, there are three ways to draw the $$$2$$$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones):  We see that the third way gives the maximum number of intersections, namely $$$4$$$.In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.In the third test case, we can make at most one intersection by drawing chords $$$1-3$$$ and $$$2-4$$$, as shown below:

'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 = () => Number(read());
  const n = rn(),
        k = rn(),
        a = new Array(k);
  const vis = new Array(n + 1);
  for (let i = 0; i < k; i++) {
    a[i] = [rn(), rn()];
    if (a[i][0] > a[i][1]) [a[i][0], a[i][1]] = [a[i][1], a[i][0]];
    vis[a[i][0]] = 1;
    vis[a[i][1]] = 1;
  }
  let nums = [];
  for (let i = 1; i <= n * 2; i++) if (!vis[i]) nums.push(i);
  const m = nums.length / 2;
  for (let i = 0; i < m; i++) a.push([nums[i], nums[i + m]]);
  let res = 0;
  for (let i = 0; i < a.length; i++) {
    for (let j = i + 1; j < a.length; j++) {
      let x = a[i],
          y = a[j];
      if (x[0] > y[0]) [x, y] = [y, x];
      if (x[1] > y[0] && x[1] < y[1]) res++;
    }
  }
  return res;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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


At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.The nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number $$$a$$$ of rows cannot be greater than $$$5$$$ while the number $$$b$$$ of columns cannot exceed $$$20$$$. Every cell of the table will contain either an asterisk («*») or a letter of user's handle.Furthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks).The organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns.The winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table.

The only line contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), comprised of uppercase and lowercase Latin letters,  — the handle of the winner.

In the first line output the minimum number $$$a$$$ of rows in the table and the minimum number $$$b$$$ of columns in an optimal table with rows. The following $$$a$$$ lines should contain $$$b$$$ characters each  — any valid table.

3 15
MyNameIsLifeIAm
ForeverByYourSi
deMyNameIsL*ife

var str = readline();
var l = str.length;

var lines = Math.ceil(l / 20);
var min = Math.floor(l / lines);
var max = Math.ceil(l / lines);
var symb = min < max ? '*' : '';
var full = l - lines * min;

var res = [];
for(var i = 0; i < full * max; i+=max) {
    res.push(str.substr(i, max));
}
for(; i < l; i+=min) {
    res.push(str.substr(i, min) + symb);
}

print('' + lines + ' ' + max);
res.forEach(v => print(v));


Polycarp is an organizer of a Berland ICPC regional event. There are $$$n$$$ universities in Berland numbered from $$$1$$$ to $$$n$$$. Polycarp knows all competitive programmers in the region. There are $$$n$$$ students: the $$$i$$$-th student is enrolled at a university $$$u_i$$$ and has a programming skill $$$s_i$$$.Polycarp has to decide on the rules now. In particular, the number of members in the team.Polycarp knows that if he chooses the size of the team to be some integer $$$k$$$, each university will send their $$$k$$$ strongest (with the highest programming skill $$$s$$$) students in the first team, the next $$$k$$$ strongest students in the second team and so on. If there are fewer than $$$k$$$ students left, then the team can't be formed. Note that there might be universities that send zero teams.The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is $$$0$$$.Help Polycarp to find the strength of the region for each choice of $$$k$$$ from $$$1$$$ to $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of universities and the number of students. The second line of each testcase contains $$$n$$$ integers $$$u_1, u_2, \dots, u_n$$$ ($$$1 \le u_i \le n$$$) — the university the $$$i$$$-th student is enrolled at. The third line of each testcase contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$) — the programming skill of the $$$i$$$-th student. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$n$$$ integers: the strength of the region — the total skill of the members of the present teams — for each choice of team size $$$k$$$.

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  nextBigArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextBigInt());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-c.ts

const io = new IO();

function solve(n, u, s) {
  let arr = [];
  let sums = []; // let uniSet = new Set<number>();

  for (let i = 0; i < n; i++) {
    let uni = u[i] - 1; // uniSet.add(uni);

    if (!arr[uni]) {
      arr[uni] = [];
    }

    arr[uni].push(s[i]);
  }

  for (let i = 0; i < arr.length; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    sub.sort((a, b) => Number(b - a));
    sums[i] = [0n];

    for (let j = 0; j < sub.length; j++) {
      sums[i][j + 1] = sums[i][j] + sub[j];
    }
  }

  let retSums = Array.from({
    length: n + 1
  }).map(() => 0n);

  for (let i = 0; i < n; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    for (let k = 1; k <= sub.length; k++) {
      let max = sub.length - sub.length % k;
      retSums[k] += sums[i][max];
    }
  } // uniSet.forEach((i) => {
  //   let sub = arr[i];
  //   for (let k = 1; k <= sub.length; k++) {
  //     let max = sub.length - (sub.length % k);
  //     retSums[k] += sums[i][max];
  //   }
  // });

  for (let k = 1; k <= n; k++) {
    io.write(retSums[k]);
  }

  io.writeLine('');
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let u = io.nextNumArray(n);
      let s = io.nextBigArray(n);
      solve(n, u, s);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  nextBigArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextBigInt());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-c.ts

const io = new IO();

function solve(n, u, s) {
  let arr = [];
  let sums = []; // let uniSet = new Set<number>();

  for (let i = 0; i < n; i++) {
    let uni = u[i] - 1; // uniSet.add(uni);

    if (!arr[uni]) {
      arr[uni] = [];
    }

    arr[uni].push(s[i]);
  }

  for (let i = 0; i < arr.length; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    sub.sort((a, b) => b - a);
    sums[i] = [0];

    for (let j = 0; j < sub.length; j++) {
      sums[i][j + 1] = sums[i][j] + sub[j];
    }
  }

  let retSums = Array.from({
    length: n + 1
  }).map(() => 0);

  for (let i = 0; i < n; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    for (let k = 1; k <= sub.length; k++) {
      let max = sub.length - sub.length % k;
      retSums[k] += sums[i][max];
    }
  } // uniSet.forEach((i) => {
  //   let sub = arr[i];
  //   for (let k = 1; k <= sub.length; k++) {
  //     let max = sub.length - (sub.length % k);
  //     retSums[k] += sums[i][max];
  //   }
  // });

  for (let k = 1; k <= n; k++) {
    io.write(retSums[k]);
  }

  io.writeLine('');
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let u = io.nextNumArray(n);
      let s = io.nextNumArray(n);
      solve(n, u, s);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  nextBigArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextBigInt());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-c.ts

const io = new IO();

function solve(n, u, s) {
  let arr = [];
  let sums = [];
  let uniSet = new Set();

  for (let i = 0; i < n; i++) {
    let uni = u[i] - 1;
    uniSet.add(uni);

    if (!arr[uni]) {
      arr[uni] = [];
    }

    arr[uni].push(s[i]);
  }

  for (let i = 0; i < arr.length; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    sub.sort((a, b) => b - a);
    sums[i] = [0];

    for (let j = 0; j < sub.length; j++) {
      sums[i][j + 1] = sums[i][j] + sub[j];
    }
  }

  let retSums = Array.from({
    length: n + 1
  }).map(() => 0);
  uniSet.forEach(i => {
    let sub = arr[i];

    for (let k = 1; k <= sub.length; k++) {
      let max = sub.length - sub.length % k;
      retSums[k] += sums[i][max];
    }
  });

  for (let k = 1; k <= n; k++) {
    io.write(retSums[k]);
  }

  io.writeLine('');
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let u = io.nextNumArray(n);
      let s = io.nextNumArray(n);
      solve(n, u, s);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  nextBigArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextBigInt());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-c.ts

const io = new IO();

function solve(n, u, s) {
  let arr = [];
  let sums = [];
  let uniMap = new Map();
  let uniSet = new Set();

  for (let i = 0; i < n; i++) {
    let uni = u[i] - 1;
    uniSet.add(uni);

    if (!arr[uni]) {
      arr[uni] = [];
    }

    arr[uni].push(s[i]); // if (!uniMap.has(uni)) {
    //   uniMap.set(uni, []);
    // }
    // uniMap.get(uni)!.push(s[i]);
  }

  for (let i = 0; i < arr.length; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    sub.sort((a, b) => b - a);
    sums[i] = [0];

    for (let j = 0; j < sub.length; j++) {
      sums[i][j + 1] = sums[i][j] + sub[j];
    }
  }

  let maxK = 0;
  uniSet.forEach(i => {
    maxK = Math.max(maxK, arr[i].length);
  }); // console.log({ maxK });
  // console.log(uniSet.size);

  let retSums = Array.from({
    length: n + 1
  }).map(() => 0); // console.log(sums);
  // console.log(uniSet);

  uniSet.forEach(i => {
    let sub = arr[i];

    for (let k = 1; k <= sub.length; k++) {
      let max = sub.length - sub.length % k; // console.log({ k, i, max });

      retSums[k] += sums[i][max];
    }
  });

  for (let k = 1; k <= n; k++) {
    io.write(retSums[k]);
  }

  io.writeLine(''); // for (let k = 1; k <= maxK; k++) {
  //   let ret = 0;
  //   uniSet.forEach((i) => {
  //     let sub = arr[i];
  //     // let max = Math.floor(sub.length / k) * k;
  //     let max = sub.length - (sub.length % k);
  //     ret += sums[i][max];
  //   });
  //   // for (let i = 0; i < arr.length; i++) {
  //   //   let sub = arr[i];
  //   //   if (!sub) {
  //   //     continue;
  //   //   }
  //   //   let max = Math.floor(sub.length / k) * k;
  //   //   ret += sums[i][max];
  //   // }
  //   io.write(ret);
  // }
  // for (let k = maxK + 1; k <= n; k++) {
  //   io.write('0');
  // }
  // io.writeLine('');
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let u = io.nextNumArray(n);
      let s = io.nextNumArray(n);
      solve(n, u, s);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

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

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

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

		const unv = Array.from(Array(n), x => []); // only n unv
		for (let i = 0; i < n; i++) {
			--u[i];
			unv[u[i]].push(s[i]);
		}

		let ans = Array(n).fill(0); // only n answers
		for (const stds of unv) {
			stds.sort((x, y) => y-x);

			const sz = stds.length;
			const pr = [0];
			for (let i = 0; i < sz; i++) {
				pr[i+1] = pr[i] + stds[i];
			}

			for (let k = 1; k <= sz; k++) {
				ans[k-1] += pr[sz - sz%k];
			}
		}

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

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

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

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

		const unv = Array.from(Array(n), x => []);
		for (let i = 0; i < n; i++) {
			unv[u[i]-1].push(s[i]);
		}

		let ans = Array(n).fill(0);
		for (const stnds of unv) {
			stnds.sort((x, y) => y-x);
			const psm = []; psm[-1] = 0;
			for (let i = 0; i < stnds.length; i++) {
				psm[i] = psm[i-1] + stnds[i];
			}
			for (let i = 1; i <= stnds.length; i++) {
				const indx = stnds.length - stnds.length%i;
				ans[i-1] += psm[indx-1]; //
			}
		}

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

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
var __webpack_exports__ = {};

;// CONCATENATED MODULE: ./src/io.js
var interact = function interact(main) {
  process.stdin.resume();
  process.stdin.setEncoding('utf-8');
  var inputString = '';
  var currentLine = 0;

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

  var print = function print() {
    for (var _len = arguments.length, any = new Array(_len), _key = 0; _key < _len; _key++) {
      any[_key] = arguments[_key];
    }

    process.stdout.write(any.join(' '));
  };

  var println = function println() {
    for (var _len2 = arguments.length, any = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      any[_key2] = arguments[_key2];
    }

    any.length > 0 && print(any);
    print('\n');
  };

  var obj = {
    print: print,
    println: println,
    readline: readline
  };
  process.stdin.on('data', function (inputStdin) {
    inputString += inputStdin;
  });
  process.stdin.on('end', function () {
    inputString = inputString.trim().split('\n').map(function (string) {
      return string.trim();
    });
    main(obj);
  });
};

/* harmony default export */ const io = (interact);
;// CONCATENATED MODULE: ./src/index.js
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

var main = function main(io) {
  var tc = parseInt(io.readline());

  while (tc--) {
    var n = parseInt(io.readline()); // O(n)

    var studentUni = io.readline().split(' ').map(function (x) {
      return parseInt(x);
    }); // O(n)

    var skill = io.readline().split(' ').map(function (x) {
      return parseInt(x);
    });
    var uss = Array(n); // O(n)

    var set = new Set();

    for (var i = 0; i < n; i++) {
      uss[i] = {
        uni: studentUni[i],
        skill: skill[i]
      };
      set.add(studentUni[i]);
    } // O(nlogn)

    uss.sort(function (a, b) {
      if (a.uni === b.uni) return b.skill - a.skill;
      return a.uni - b.uni;
    }); // O(n)

    var uni = [];
    var prevUni = 0; // O(n)

    for (var _i = 0, _uss = uss; _i < _uss.length; _i++) {
      var ussItem = _uss[_i];

      if (prevUni !== ussItem.uni) {
        prevUni = ussItem.uni;
        uni.push([ussItem.skill]);
      } else {
        var prevUniLength = uni[uni.length - 1].length;
        var prevSkillSum = prevUniLength === 0 ? 0 : uni[uni.length - 1][prevUniLength - 1];
        var nextSkillSum = prevSkillSum + ussItem.skill;
        uni[uni.length - 1].push(nextSkillSum);
      }
    }

    uni.sort(function (a, b) {
      return b.length - a.length;
    });
    var res = [];

    a1: for (var k = 1; k <= n; k++) {
      res.push(0);

      var _iterator = _createForOfIteratorHelper(uni),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var uniItem = _step.value;
          if (k > uniItem.length) continue a1;
          var index = Math.floor(uniItem.length / k) * k - 1;
          if (index < 0) continue;
          res[k - 1] += uniItem[index];
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }

    io.println(res.join(' '));
  }
};

io(main);
/******/ })()
;

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var u = readline().split(' ').map(a => parseInt(a));
  var s = readline().split(' ').map(a => parseInt(a));
  var a = [];
  var power = new Array(n + 1).fill(0);
  u.forEach((el, i) => {
    if (!a[el])
      a[el] = new Array();
    a[el].push(s[i]);
  });

  for (var i = 1; i <= n; i++)
    if (a[i]) {
      a[i].sort((a, b) => b - a);
      var len = a[i].length ;
      for (var j = 1; j < len; j++)
        a[i][j] += a[i][j - 1];
      for (var j = 1; j <= len; j++) {
        var x = parseInt(len / j) * j;
        power[j] += a[i][x - 1];
      }
    }

  for (var i = 1; i <= n; i++)
    write(`${power[i]} `);
  write('\n');
}

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-c.ts

const io = new IO();

function solve(n, u, s) {
  let arr = [];
  let sums = [];
  let uniMap = new Map();
  let uniSet = new Set();

  for (let i = 0; i < n; i++) {
    let uni = u[i] - 1;
    uniSet.add(uni);

    if (!arr[uni]) {
      arr[uni] = [];
    }

    arr[uni].push(s[i]); // if (!uniMap.has(uni)) {
    //   uniMap.set(uni, []);
    // }
    // uniMap.get(uni)!.push(s[i]);
  }

  for (let i = 0; i < arr.length; i++) {
    let sub = arr[i];

    if (!sub) {
      continue;
    }

    sub.sort((a, b) => b - a);
    sums[i] = [0];

    for (let j = 0; j < sub.length; j++) {
      sums[i][j + 1] = sums[i][j] + sub[j];
    }
  }

  let maxK = 0;
  uniSet.forEach(i => {
    maxK = Math.max(maxK, arr[i].length);
  });

  for (let k = 1; k <= maxK; k++) {
    let ret = 0;
    uniSet.forEach(i => {
      let sub = arr[i];
      let max = Math.floor(sub.length / k) * k;
      ret += sums[i][max];
    }); // for (let i = 0; i < arr.length; i++) {
    //   let sub = arr[i];
    //   if (!sub) {
    //     continue;
    //   }
    //   let max = Math.floor(sub.length / k) * k;
    //   ret += sums[i][max];
    // }

    io.write(ret);
  }

  for (let k = maxK + 1; k < n; k++) {
    io.write('0');
  }

  io.writeLine('');
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let u = io.nextNumArray(n);
      let s = io.nextNumArray(n);
      solve(n, u, s);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 747:
/***/ ((module) => {

module.exports = require("fs");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(747);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// CONCATENATED MODULE: external "readline"
const external_readline_namespaceObject = require("readline");;
;// CONCATENATED MODULE: ./src/lib/io.ts

class InteractiveIO {
  constructor() {
    this.rl = void 0;
    this.lines = [];
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    this.rl.on('line', line => {
      this.lines.push(line);
    });
  }

  nextLine() {
    return new Promise((resolve, reject) => {
      if (this.lines.length) {
        resolve(this.lines.shift());
        return;
      }

      let waitId = null;
      let timeoutId = null;
      waitId = setInterval(() => {
        if (this.lines.length) {
          resolve(this.lines.shift());
          clearTimeout(timeoutId);
          clearInterval(waitId);
          return;
        }
      }, 1);
      timeoutId = setTimeout(() => {
        clearInterval(waitId);
        reject(new Error('timeout')); // resolve(null);
      }, 500);
    });
  }

  close() {
    this.rl.close();
  }

}
class IO {
  constructor() {
    this.i = 0;
    this.text = '';
    this.out = '';
    this.readInput();
  }

  readInput() {
    this.text = __webpack_require__(747).readFileSync(0, 'utf8');
  }

  nextToken() {
    let ret = '';

    while (this.text[this.i].charCodeAt(0) <= 32) {
      this.i++;
    }

    while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
      ret += this.text[this.i];
      this.i++;
    }

    return ret;
  }

  nextNum() {
    return Number(this.nextToken());
  }

  nextBigInt() {
    return BigInt(this.nextToken());
  }

  nextNumArray(n) {
    let ret = [];

    while (n--) {
      ret.push(this.nextNum());
    }

    return ret;
  }

  _write(x) {
    this.out += x;
  }

  write(x) {
    this._write(x + ' ');
  }

  writeLine(x) {
    this._write(x + '\n');
  }

  flush() {
    external_fs_default().writeFileSync(1, this.out);
    this.out = '';
  }

}
;// CONCATENATED MODULE: ./src/cf-1519/1519-c.ts

const io = new IO();

function solve(n, u, s) {
  let arr = [];
  let sums = [];

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

    if (!arr[uni]) {
      arr[uni] = [];
    }

    arr[uni].push(s[i]);
  }

  arr.forEach((sub, i) => {
    sub.sort((a, b) => b - a);
    sums[i] = [0];
    sub.forEach((a, j) => {
      sums[i][j + 1] = sums[i][j] + a;
    });
  });
  let maxK = 0;
  arr.forEach(sub => {
    maxK = Math.max(sub.length, maxK);
  });

  for (let k = 1; k <= maxK; k++) {
    let ret = 0;
    arr.forEach((sub, i) => {
      if (!sub) {
        return;
      }

      let max = Math.floor(sub.length / k) * k;
      ret += sums[i][max];
    });
    io.write(ret);
  }

  io.writeLine('');
}

function main() {
  try {
    let t = io.nextNum();

    while (t--) {
      let n = io.nextNum();
      let u = io.nextNumArray(n);
      let s = io.nextNumArray(n);
      solve(n, u, s);
    }

    io.flush();
  } catch (e) {
    console.log(e.stack);
  }
}

main();

})();

/******/ })()
;

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var u = readline().split(' ').map(a => parseInt(a));
  var s = readline().split(' ').map(a => parseInt(a));
  var a = [];
  var power = [];
  u.forEach((el, i) => {
    if (!a[el])
      a[el] = new Array();
    a[el].push(s[i]);
  });

  for (var i = 0; i < n; i++) {
		var len = a[i]? a[i].length: 0;
		for (var j = 0; j < len - 1; j++)
			a[i][j] += a[i][j - 1];
		for (var j = 0; j < len; j++) {
			var x = parseInt(len / j) * j;
			power[j] += a[i][x - 1];
		}
	}

  for (var i = 0; i < n; i++)
    write(`${power[i]} `);
  write('\n');
}


Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of students and the number of subjects, correspondingly. Next n lines each containing m characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.

Print the single number — the number of successful students in the given group.

NoteIn the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.In the second sample test each student is the best at at least one subject.

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

rl.on('line', (d) => {
  if (c === 0) {
    [n, m] = d.split(' ').map(Number);
    c++;
    return;
  }

  const marks = d;
  students.push(marks);

  c++;
});

rl.on('close', () => {
  const bests = new Set();

  for (let i = 0; i < students[0].length; i++) {
    let best = 0;
    for (let j = 0; j < students.length; j++) {
      if (students[j][i] > best) {
        best = students[j][i];
      }
    }

    for (let z = 0; z < students.length; z++) {
      if (students[z][i] === best) {
        bests.add(z);
      }
    }
  }

  console.log(bests.size);
});

print(function(n, m) {
	var i, j,
		a = [],
		b = new Int8Array(n);

	for (i = 0; i < n; i++)
		a.push(readline().split('').map(Number));

	for (i = 0; i < m; i++) {
		var max = 0;

		for (j = 0; j < n; j++)
			max = Math.max(a[j][i], max);

		for (j = 0; j < n; j++)
			if (a[j][i] === max) b[j] = 1;
	}

	var ans = 0;
	for (i = 0; i < n; i++)
		if (b[i] === 1) ans++;

	return ans;

}.apply(0, readline().split(' ').map(Number)));

print(function(n, m) {
	var i, j,
		a = [],
		b = [];

	for (i = 0; i < n; i++) {
		a.push(readline().split('').map(Number));
		b.push(0);
	}

	for (i = 0; i < m; i++) {
		var max = 0;

		for (j = 0; j < n; j++)
			max = Math.max(a[j][i], max);

		for (j = 0; j < n; j++)
			if (a[j][i] === max) b[j] = 1;
	}

	return b.filter(function(v) {
		return v === 1;
	}).length;

}.apply(0, readline().split(' ').map(Number)));

;(function () {

	var n = readline().split(' ');
	var m = +n[1];
	n = +n[0];

	var u = [];
	for (var i = 0; i < n; i++) u.push(readline().split('').map(Number));

	var s = {};
	for (var i = 0; i < m; i++) {
		var l = u.map(function (e) { return e[i]; });
		var max = Math.max.apply(null, l);
		l.forEach(function (e, i) { if (e == max) s[i] = true; });
	}

	print( Object.keys(s).length );

}).call(this);