You are given $n$ integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the $n$ numbers may not be chosen.

A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.

What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.


-----Input-----

The first line contains $n$ ($1 \le n \le 4\cdot10^5$). The second line contains $n$ integers ($1 \le a_i \le 10^9$).


-----Output-----

In the first line print $x$ ($1 \le x \le n$) — the total number of cells of the required maximum beautiful rectangle. In the second line print $p$ and $q$ ($p \cdot q=x$): its sizes. In the next $p$ lines print the required rectangle itself. If there are several answers, print any.


-----Examples-----
Input
12
3 1 4 1 5 9 2 6 5 3 5 8

Output
12
3 4
1 2 3 5
3 1 5 4
5 6 8 9

Input
5
1 1 1 1 1

Output
1
1 1
1

Difficulty: HARD
Tags: Constructive algorithms

Combinatorics

Complete search

Greedy algorithms

Mathematics

Data structures
Skill types: Complete search

Data structures

Greedy algorithms

Starter code:

Solutions:
import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
from collections import Counter
C = Counter(A)
import math
MAXV = max(max(C.values()), int(math.sqrt(n)))
VCOUNT = [0] * (MAXV + 1)
for v in list(C.values()):
	VCOUNT[v] += 1
SUM = n
from itertools import accumulate
ACC = list(accumulate(VCOUNT[::-1]))[::-1]
ANS = 0
for i in range(MAXV, 0, -1):
	if SUM // i >= i:
		if ANS < i * (SUM // i):
			ANS = i * (SUM // i)
			ANSX = (i, SUM // i)
	SUM -= ACC[i]
print(ANS)
(X, Y) = (ANSX[0], ANSX[1])
print(X, Y)
A = [[0] * Y for i in range(X)]
i = 0
j = 0
nowj = 0
colored = 0
same = 0
LIST = list(C.most_common())
ind = 0
while colored < ANS:
	(A[i][j], MAX) = LIST[ind]
	colored += 1
	i += 1
	j = (j + 1) % Y
	if i == X:
		i = 0
		nowj += 1
		j = nowj
	same += 1
	if same == min(X, MAX):
		ind += 1
		same = 0
for a in A:
	sys.stdout.write(' '.join(map(str, a)) + '\n')


n = int(input())
l = list(map(int, input().split()))
if n == 1:
	print(1)
	print(1, 1)
	print(l[0])
else:
	d = {}
	for i in l:
		d[i] = 0
	for i in l:
		d[i] += 1
	equal = [0] * (n + 1)
	for i in d:
		equal[d[i]] += 1
	atmost = [0] * (n + 1)
	atmost[0] = equal[0]
	for i in range(1, n + 1):
		atmost[i] = atmost[i - 1] + equal[i]
	sumka = 0
	best_iloczyn = 0
	best_a = 0
	best_b = 0
	for a in range(1, n):
		if a ** 2 > n:
			break
		sumka += len(d) - atmost[a - 1]
		b_cand = sumka // a
		if b_cand < a:
			continue
		if a * b_cand > best_iloczyn:
			best_iloczyn = a * b_cand
			best_a = a
			best_b = b_cand
	print(best_iloczyn)
	print(best_a, best_b)
	li = []
	for i in d:
		if d[i] >= best_a:
			li += [i] * min(best_a, d[i])
	for i in d:
		if d[i] < best_a:
			li += [i] * min(best_a, d[i])
	mat = [[0] * best_b for i in range(best_a)]
	for dd in range(1, best_a + 1):
		if best_a % dd == 0 and best_b % dd == 0:
			du = dd
	i = 0
	for st in range(du):
		for j in range(best_iloczyn // du):
			mat[i % best_a][(st + i) % best_b] = li[i]
			i += 1
	for i in range(best_a):
		print(*mat[i])


def play(arr):
	n = len(arr)
	number2Count = {}
	for p in arr:
		number2Count[p] = number2Count.get(p, 0) + 1
	count2Numbers = {}
	maxCnt = 0
	for num in number2Count:
		cnt = number2Count[num]
		if not cnt in count2Numbers:
			count2Numbers[cnt] = []
		count2Numbers[cnt].append(num)
		maxCnt = max(maxCnt, cnt)
	numRepeats = [0] * (n + 1)
	numRepeats[n] = len(count2Numbers.get(n, []))
	for i in range(n - 1, 0, -1):
		numRepeats[i] = numRepeats[i + 1] + len(count2Numbers.get(i, []))
	a_ideal = 0
	b_ideal = 0
	square = 0
	square_ideal = 0
	for a in range(1, n + 1):
		square += numRepeats[a]
		b = int(square / a)
		if a <= b:
			if square_ideal < a * b:
				square_ideal = a * b
				a_ideal = a
				b_ideal = b
	print(a_ideal * b_ideal)
	print(str(a_ideal) + ' ' + str(b_ideal))
	matrix = [[0] * b_ideal for p in range(0, a_ideal)]
	x = 0
	y = 0
	for cnt in range(maxCnt, 0, -1):
		for num in count2Numbers.get(cnt, []):
			for i in range(0, min(cnt, a_ideal)):
				if matrix[x][y] > 0:
					x = (x + 1) % a_ideal
				if matrix[x][y] == 0:
					matrix[x][y] = num
				x = (x + 1) % a_ideal
				y = (y + 1) % b_ideal
	for i in range(0, a_ideal):
		print(*matrix[i])

def main():
	input()
	arr = list(map(int, input().split()))
	play(arr)
main()


from collections import Counter
from sys import stdin

def input():
	return next(stdin)[:-1]

def main():
	n = int(input())
	aa = input().split()
	cc = list(Counter(aa).most_common())
	if n % cc[0][1] == 0 and cc[0][1] * cc[0][1] <= n:
		h = cc[0][1]
		w = n // cc[0][1]
		best = n
	else:
		count_count = [0] * (n + 1)
		for (v, c) in cc:
			count_count[c] += 1
		geq = [count_count[n]]
		for v in reversed(count_count[:n]):
			geq.append(geq[-1] + v)
		geq.reverse()
		tot = 0
		best = 0
		for a in range(1, n + 1):
			tot += geq[a]
			b = tot // a
			if a <= b and best < a * b:
				best = a * b
				h = a
				w = b
	print(best)
	print(h, w)
	x = 0
	y = 0
	mat = [[''] * w for _ in range(h)]
	for (v, c) in cc:
		for j in range(min(c, h)):
			if mat[x][y] != '':
				x = (x + 1) % h
			if mat[x][y] == '':
				mat[x][y] = v
			x = (x + 1) % h
			y = (y + 1) % w
	for i in range(h):
		print(' '.join(mat[i]))
main()


from collections import Counter
from itertools import accumulate
from math import sqrt
from operator import itemgetter
import sys
n = int(input())
cnt = Counter(map(int, input().split()))
(nums, counts) = zip(*sorted(cnt.items(), key=itemgetter(1)))
acc = [0] + list(accumulate(counts))
area = 1
(h, w) = (1, 1)
i = len(counts)
for y in range(int(sqrt(n)), 0, -1):
	while i and counts[i - 1] > y:
		i -= 1
	total = acc[i] + (len(counts) - i) * y
	x = total // y
	if y <= x and area < x * y:
		(h, w, area) = (y, x, x * y)
ans = [[0] * w for _ in range(h)]
i = len(counts) - 1
(num, count) = (nums[i], min(h, counts[i]))
for x in range(w):
	for y in range(h):
		ans[y][(x + y) % w] = num
		count -= 1
		if count == 0:
			i -= 1
			(num, count) = (nums[i], h if h < counts[i] else counts[i])
print(area)
print(h, w)
for y in range(h):
	sys.stdout.write(' '.join(map(str, ans[y])) + '\n')


n = int(input())
arr = list(map(int, input().split()))
d = {}
for i in arr:
	d[i] = d.get(i, 0) + 1
d2 = {}
for (k, v) in d.items():
	d2.setdefault(v, []).append(k)
s = n
prev = 0
ansp = ansq = anss = 0
for p in range(n, 0, -1):
	q = s // p
	if p <= q and q * p > anss:
		anss = q * p
		ansq = q
		ansp = p
	prev += len(d2.get(p, []))
	s -= prev

def get_ans():
	cur_i = 0
	cur_j = 0
	cur = 0
	for (k, v) in d3:
		for val in v:
			f = min(k, anss - cur, ansp)
			cur += f
			for i in range(f):
				cur_i = (cur_i + 1) % ansp
				cur_j = (cur_j + 1) % ansq
				if ans[cur_i][cur_j]:
					cur_i = (cur_i + 1) % ansp
				ans[cur_i][cur_j] = val
print(anss)
print(ansp, ansq)
d3 = sorted(d2.items(), reverse=True)
ans = [[0] * ansq for i in range(ansp)]
get_ans()
for i in range(ansp):
	print(*ans[i])


from itertools import accumulate
import math
from collections import Counter
import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
D = Counter(A)
MAXV = max(max(D.values()), int(math.sqrt(n)))
VCOUNT = [0] * (MAXV + 1)
for v in D.values():
	VCOUNT[v] += 1
SUM = n
ACC = list(accumulate(VCOUNT[::-1]))[::-1]
ANS = 0
for i in range(MAXV, 0, -1):
	if SUM // i >= i:
		if ANS < i * (SUM // i):
			ANS = i * (SUM // i)
			ANSX = (i, SUM // i)
	SUM -= ACC[i]
print(ANS)
(X, Y) = (ANSX[0], ANSX[1])
print(X, Y)
(maxx, a, b) = (ANS, X, Y)
A = []
D = D.most_common()
for (key, d) in D:
	num = min(a, d)
	for number in range(num):
		A.append(key)
ANS = [[0] * b for _ in range(a)]
AIM = A[:maxx]
pos = 0
turn = 0
while True:
	posi = 0
	posj = turn
	for i in range(a):
		ANS[(posi + i) % a][(posj + i) % b] = AIM[pos]
		pos += 1
	if pos == maxx:
		break
	turn += 1
for ans in ANS:
	sys.stdout.write(' '.join(map(str, ans)) + '\n')


from sys import stdin, stdout

def getmaxrectangle(n, a):
	dic = {}
	dicCntVals = {}
	for va in a:
		if va not in dic:
			dic[va] = 0
		dic[va] += 1
	for val in dic.keys():
		cnt = dic[val]
		if cnt not in dicCntVals:
			dicCntVals[cnt] = []
		dicCntVals[cnt].append(val)
	geq = [0] * (n + 1)
	if n in dicCntVals:
		geq[n] = len(dicCntVals[n])
	for cnt in range(n - 1, 0, -1):
		geq[cnt] = geq[cnt + 1]
		if cnt in dicCntVals:
			geq[cnt] += len(dicCntVals[cnt])
	b_pq = 0
	b_p = 0
	b_q = 0
	ttl = 0
	for p in range(1, n + 1):
		ttl += geq[p]
		q = int(ttl / p)
		if q >= p and q * p > b_pq:
			b_pq = q * p
			b_p = p
			b_q = q
	x = 0
	y = 0
	r = [[0 for j in range(b_q)] for i in range(b_p)]
	for i in range(n, 0, -1):
		if i not in dicCntVals:
			continue
		for j in dicCntVals[i]:
			for k in range(min(b_p, i)):
				if r[x][y] != 0:
					x = (x + 1) % b_p
				if r[x][y] == 0:
					r[x][y] = j
				x = (x + 1) % b_p
				y = (y + 1) % b_q
	return r
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
res = getmaxrectangle(n, a)
stdout.write(str(len(res) * len(res[0])))
stdout.write('\n')
stdout.write(str(len(res)) + ' ' + str(len(res[0])))
stdout.write('\n')
for i in range(len(res)):
	for j in range(len(res[i])):
		stdout.write(str(res[i][j]))
		stdout.write(' ')
	stdout.write('\n')