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

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 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(" ")
        .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);
}

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. 겹치기 불가능
*/


/******/ (() => { // 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');
}


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


//var input = readline()
var n = parseInt(readline())

print(n)
var arr = new Array(n).fill(1)
print(arr.join(' '))

//

var n = +readline();

print(n);
var res = '';
for(var i = 0; i < n; i++) {
   res += '1 ';
}
print(res);

function main(n){

      print(n);
      var ans = ""
      for(var i = 0 ; i < n ; i++){
        ans += "1 ";
      }

      print(ans);
}

var n = parseInt(readline());

main(n);

var k = Number(readline())
var arr = new Array(k).fill(1)
print(k)
print(arr.join(" "))

var n = parseInt(readline());
write(n + "\n");
write(Array(n).fill(1).join(" "));

var taka = parseInt(readline());
print(taka);

for (var i = 1; i <= taka; i++) {
    print(1 + ' ');
}

var num = parseInt(readline());
print(num);
for(var i = 1; i <= num; i++){
    print(1 + ' ');
}

//var input = readline();
var T = parseInt(readline());

print(T);
for(var i=0; i<T; i++) {
     print(1 +' ');
}

//

var t = parseInt(readline())

print(t)
for(var i=0; i<t; i++) {
    write(1 +' ')
}

//Don't have to see. start------------------------------------------
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);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
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){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var output = new Array(N);
  for(var i = 0; i < N; i++){
    output[i] = 1;
  }
  myout(N);
  myout(myconv(output, 8));
}

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

rl.on('line', (d) => {
  let n = +d;
  let divider = 9;

  while(n % divider !== 0) {
    divider--;
  }

  console.log(n / divider);
  console.log(new Array(n / divider).fill(divider).join(' '));
});

var N = 0;
var readliner = require('readline');
var rl = readliner.createInterface(process.stdin, process.stdout, null);
rl.on('line', function (cmd) {
                  //console.log('You just typed: '+cmd);
                  N = parseInt(cmd);
              }).on('close', main);

function main() {
    //console.log('goodbye!');

/*    var mn = 1000000000;
    for (var code=0; code<(1<<9); code++) {
	var cnt_ones = 0;
	for (var j=0; j<9; j++) cnt_ones += (code>>j)&1;
        var x = N;

    }*/

    console.log(N);
    var ans = "";
    for (var j=0; j<N; j++) ans += "1 ";
    console.log(ans);

    //var x = 1.2345678;
    //console.log('x = ',Number(x).toFixed(5));

    process.exit(0);
};

//var lines = data.split(/\r?\n/);

function ansa(num){

    var bolur = Infinity;
    var anse = ""
    if(num === 1){
      print("1")
      print("1")
      return;
    }
    for(var i = 2 ; i < num ; i++){
      if(num % i === 0 && bolur > i ){
        bolur = i;
      }
    }
    print(bolur);
    for(var i = 0 ; i < bolur ; i++){
      anse = anse + (num/bolur) + " "
    }
    print(anse);

}

var line = readline();
// for(var i = 0 ; i < line.length ; i++) line[i] = parseInt(line[i]);
// var line2 = readline().split(' ');
// for(var i = 0 ; i < line2.length ; i++) line2[i] = parseInt(line2[i]);

ansa(parseInt(line));

var n = parseInt(readline());
var max = Math.min(9, n);
var nums = parseInt(n / max);
var results = new Array(nums).fill(max);
if (n % max !== 0) {
    nums++;
    results.push(n % max);
}

write(results.length);
write(results.join(" "));

var n = parseInt(readline());
var max = Math.min(9, n);
var nums = parseInt(n / max);
var results = new Array(nums).fill(max);
if (n % max !== 0) {
    nums++;
    results.push(n % max);
}

write(results.length + "\n");
write(results.join(" "));