You are given a binary string $s$ consisting of $n$ zeros and ones.

Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).

Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".

You have to answer $t$ independent test cases.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the test case contains $n$ characters '0' and '1' — the string $s$.

It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).


-----Output-----

For each test case, print the answer: in the first line print one integer $k$ ($1 \le k \le n$) — the minimum number of subsequences you can divide the string $s$ to. In the second line print $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the number of subsequence the $i$-th character of $s$ belongs to.

If there are several answers, you can print any.


-----Example-----
Input
4
4
0011
6
111111
5
10101
8
01010000

Output
2
1 2 2 1 
6
1 2 3 4 5 6 
1
1 1 1 1 1 
4
1 1 1 1 1 2 3 4

Source: codeforces | Difficulty: MEDIUM
Tags: Greedy algorithms

Data structures

Implementation

Constructive algorithms


Solutions:
for _ in range(int(input())):
	n = int(input())
	a = []
	b = 0
	o = []
	z = []
	for x in input():
		if '0' == x:
			if o:
				z += (o.pop(),)
				a += (z[-1],)
			else:
				b += 1
				z += (b,)
				a += (b,)
		elif z:
			o += (z.pop(),)
			a += (o[-1],)
		else:
			b += 1
			o += (b,)
			a += (b,)
	print(b)
	print(*a)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = input()
	zeroList = []
	oneList = []
	result = [0] * len(arr)
	ind = 0
	getit = 1
	for i in arr:
		if i == '0':
			if len(oneList) > 0:
				result[ind] = oneList.pop()
				zeroList.append(result[ind])
			else:
				result[ind] = getit
				zeroList.append(getit)
				getit = getit + 1
		elif len(zeroList) > 0:
			result[ind] = zeroList.pop()
			oneList.append(result[ind])
		else:
			result[ind] = getit
			oneList.append(getit)
			getit = getit + 1
		ind += 1
	print(max(result))
	print(*result)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 1000000007

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	s = [int(i) for i in input()]
	stacks = 0
	inSearch = defaultdict(list)
	ans = []
	for i in s:
		if len(inSearch[i]) > 0:
			X = inSearch[i].pop()
			ans.append(X)
			inSearch[i ^ 1].append(X)
		else:
			stacks += 1
			inSearch[i ^ 1].append(stacks)
			ans.append(stacks)
	print(stacks)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ones = [[] for __ in range(2)]
	ans = [0] * n
	cnt = 0
	for i in range(n):
		x = int(s[i]) ^ 1
		if not ones[x]:
			cnt += 1
			ans[i] = cnt
		else:
			ans[i] = ones[x][-1]
			ones[x].pop()
		ones[x ^ 1].append(ans[i])
	print(cnt)
	print(*ans)


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	ones = [-1 for i in range(n)]
	io = 0
	zero = [-1 for i in range(n)]
	iz = 0
	j = 1
	ans = [0 for i in range(n)]
	for i in range(n):
		if s[i] == '0':
			if io > 0:
				ans[i] = ones[io - 1]
				io -= 1
			else:
				ans[i] = str(j)
				j += 1
			zero[iz] = ans[i]
			iz += 1
		else:
			if iz > 0:
				ans[i] = zero[iz - 1]
				iz -= 1
			else:
				ans[i] = str(j)
				j += 1
			ones[io] = ans[i]
			io += 1
	print(j - 1)
	print(' '.join(ans))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for j in range(int(input())):
	n = int(input())
	vals = [int(k) for k in input()]
	ans = []
	cv = 1
	ones = 0
	zeros = 0
	dict0 = {}
	k0 = set([])
	dict1 = {}
	k1 = set([])
	ans = []
	if vals[0] == 0:
		zeros += 1
		dict0[cv] = (cv, set([0]))
		k0.add(cv)
	else:
		ones += 1
		dict1[cv] = (cv, set([0]))
		k1.add(cv)
	ans.append(cv)
	for s in range(1, n):
		if vals[s] == 0:
			if ones > 0:
				c1 = k1.pop()
				counter = dict1.pop(c1)
				ind = counter[0]
				setty = counter[1]
				setty.add(s)
				dict0[ind] = (ind, setty)
				k0.add(c1)
				ans.append(ind)
				ones -= 1
			else:
				cv += 1
				dict0[cv] = (cv, set([s]))
				ans.append(cv)
				k0.add(cv)
			zeros += 1
		else:
			if zeros > 0:
				c1 = k0.pop()
				counter = dict0.pop(c1)
				ind = counter[0]
				setty = counter[1]
				setty.add(s)
				dict1[ind] = (ind, setty)
				k1.add(c1)
				ans.append(ind)
				zeros -= 1
			else:
				cv += 1
				dict1[cv] = (cv, set([s]))
				ans.append(cv)
				k1.add(cv)
			ones += 1
	print(cv)
	print(*ans)


import bisect
import math
for xoxo in range(1):
	for _ in range(int(input())):
		n = int(input())
		s = input()
		(zero, one) = ([], [])
		(z, o, x) = (0, 0, 1)
		ans = []
		for i in range(n):
			if s[i] == '1':
				if not o < len(one):
					ans.append(x)
					zero.append(x)
					x += 1
				else:
					ans.append(one[o])
					zero.append(one[o])
					o += 1
			elif not z < len(zero):
				ans.append(x)
				one.append(x)
				x += 1
			else:
				ans.append(zero[z])
				one.append(zero[z])
				z += 1
		print(max(ans))
		print(*ans)


from sys import stdin
import sys
tt = int(stdin.readline())
for loop in range(tt):
	n = int(stdin.readline())
	a = stdin.readline()
	a = a[:-1]
	zero = []
	one = []
	ans = []
	for i in a:
		if i == '0':
			if len(zero) == 0:
				zero.append(len(zero) + len(one) + 1)
			ans.append(zero[-1])
			one.append(zero[-1])
			del zero[-1]
		else:
			if len(one) == 0:
				one.append(len(zero) + len(one) + 1)
			ans.append(one[-1])
			zero.append(one[-1])
			del one[-1]
	print(len(zero) + len(one))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cnt0 = 0
	cnt1 = 0
	for i in range(n):
		if s[i] == '1':
			cnt1 += 1
		else:
			cnt0 += 1
	pos = [[], []]
	cnt = 1
	ans = []
	for i in range(n):
		if s[i] == '1':
			if len(pos[0]) == 0:
				ans.append(cnt)
				pos[1].append(cnt)
				cnt += 1
			else:
				ans.append(pos[0][-1])
				pos[1].append(pos[0][-1])
				pos[0].pop()
		if s[i] == '0':
			if len(pos[1]) == 0:
				ans.append(cnt)
				pos[0].append(cnt)
				cnt += 1
			else:
				ans.append(pos[1][-1])
				pos[0].append(pos[1][-1])
				pos[1].pop()
	print(cnt - 1)
	print(*ans)


from sys import stdin
nii = lambda : map(int, stdin.readline().split())
lnii = lambda : list(map(int, stdin.readline().split()))
from collections import deque
t = int(input())
for tt in range(t):
	n = int(input())
	s = input()
	que0 = deque()
	que1 = deque()
	ans = []
	cnt = 0
	for i in s:
		if i == '0':
			if not que1:
				cnt += 1
				que0.append(cnt)
				ans.append(cnt)
			else:
				num = que1.popleft()
				que0.append(num)
				ans.append(num)
		elif not que0:
			cnt += 1
			que1.append(cnt)
			ans.append(cnt)
		else:
			num = que0.popleft()
			que1.append(num)
			ans.append(num)
	print(max(ans))
	print(*ans)


def solve(s, n):
	cur = [set(), set()]
	used = 1
	ans = [1]
	if s[0] == '0':
		cur[0].add(0)
	else:
		cur[1].add(0)
	for c in s[1:]:
		if c == '0' and len(cur[1]) != 0:
			i = cur[1].pop()
			cur[0].add(i)
			ans.append(i + 1)
		elif c == '1' and len(cur[0]) != 0:
			i = cur[0].pop()
			cur[1].add(i)
			ans.append(i + 1)
		else:
			used += 1
			ans.append(used)
			if c == '0':
				cur[0].add(used - 1)
			else:
				cur[1].add(used - 1)
	print(used)
	print(*ans)
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	solve(s, n)


for _ in range(int(input())):
	n = int(input())
	s = input()
	s0 = []
	s1 = []
	c = 1
	ans = []
	for i in s:
		if i == '1':
			if len(s0) == 0:
				s1.append(c)
				ans.append(c)
				c += 1
			else:
				a = s0.pop()
				s1.append(a)
				ans.append(a)
		elif len(s1) == 0:
			s0.append(c)
			ans.append(c)
			c += 1
		else:
			a = s1.pop()
			s0.append(a)
			ans.append(a)
	print(c - 1)
	print(*ans)


T = int(input())
for _ in range(T):
	N = int(input())
	s = list(input())
	d = {'0': [], '1': []}
	move = 0
	ans = []
	for c in s:
		if c == '1':
			arr = d['0']
			if not len(arr) == 0:
				tmp = arr.pop()
				ans.append(tmp)
				d['1'].append(tmp)
			else:
				move += 1
				ans.append(move)
				d['1'].append(move)
		else:
			arr = d['1']
			if not len(arr) == 0:
				tmp = arr.pop()
				ans.append(tmp)
				d['0'].append(tmp)
			else:
				move += 1
				ans.append(move)
				d['0'].append(move)
	print(move)
	print(*ans)


def check(a):
	(lst0, lst1, l, k) = ([], [], [], 1)
	for ele in a:
		if ele == '0':
			if len(lst1) == 0:
				lst0.append(k)
				l.append(k)
				k += 1
			else:
				l.append(lst1[-1])
				lst0.append(lst1[-1])
				lst1.pop()
		elif len(lst0) == 0:
			lst1.append(k)
			l.append(k)
			k += 1
		else:
			l.append(lst0[-1])
			lst1.append(lst0[-1])
			lst0.pop()
	print(k - 1)
	print(' '.join(list(map(str, l))))
for _ in range(int(input())):
	b = int(input())
	a = input()
	check(a)


from sys import stdin, stdout
fullans = ''
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = stdin.readline()
	ar = [-1] * n
	ar[0] = 1
	ans = ''
	ans += str(ar[0]) + ' '
	cnt = 1
	zerostack = []
	onestack = []
	if int(s[0]):
		onestack.append(1)
	else:
		zerostack.append(1)
	for i in range(1, n):
		if int(s[i]):
			if len(zerostack) == 0:
				cnt += 1
				onestack.append(cnt)
				ar[i] = cnt
				ans += str(ar[i]) + ' '
			else:
				elem = zerostack.pop()
				onestack.append(elem)
				ar[i] = elem
				ans += str(ar[i]) + ' '
		elif len(onestack) == 0:
			cnt += 1
			zerostack.append(cnt)
			ar[i] = cnt
			ans += str(ar[i]) + ' '
		else:
			elem = onestack.pop()
			zerostack.append(elem)
			ar[i] = elem
			ans += str(ar[i]) + ' '
	fullans += str(len(set(ar))) + '\n'
	fullans += ans + '\n'
stdout.write(fullans)


from collections import deque
for _ in range(int(input())):
	n = int(input())
	a = list(input())
	ans = [0] * n
	ans[0] = 1
	one = deque()
	zero = deque()
	curr = 1
	for i in range(n):
		if a[i] == '0':
			if len(one) > 0:
				zero.append(one.pop())
				ans[i] = zero[-1]
			else:
				zero.append(curr)
				ans[i] = zero[-1]
				curr += 1
		else:
			if len(zero) > 0:
				one.append(zero.pop())
			else:
				one.append(curr)
				curr += 1
			ans[i] = one[-1]
	print(max(ans))
	print(*ans)


import math
import sys
import bisect
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	d = {}
	d['0'] = []
	d['1'] = []
	c = 1
	ans = [0] * n
	for i in range(n):
		if s[i] == '0':
			if len(d['1']) != 0:
				val = d['1'].pop()
				d[s[i]].append(val)
			else:
				d[s[i]].append(c)
				c += 1
		elif len(d['0']) != 0:
			val = d['0'].pop()
			d[s[i]].append(val)
		else:
			d[s[i]].append(c)
			c += 1
		ans[i] = d[s[i]][-1]
	print(max(ans[:]))
	print(*ans)


import sys

def solve(n, s):
	ans = []
	(a, b) = ([], [])
	tg = 0
	for x in s:
		if x == '0':
			if not b:
				tg += 1
				a.append(tg)
			else:
				g = b.pop()
				a.append(g)
			ans.append(a[-1])
		else:
			if not a:
				tg += 1
				b.append(tg)
			else:
				g = a.pop()
				b.append(g)
			ans.append(b[-1])
	return (tg, ans)
t = int(input())
for _ in range(t):
	ln1 = next(sys.stdin)
	n = int(ln1)
	ln2 = next(sys.stdin)
	s = ln2.strip()
	(k, a) = solve(n, s)
	print(k)
	print(' '.join(map(str, a)))


import math
from collections import Counter
import math
for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = [0] * n
	ans[0] = 1
	var = s[0]
	p = 1
	v1 = []
	v2 = []
	if s[0] == '0':
		v2.append(1)
	else:
		v1.append(1)
	for i in range(1, n):
		if s[i] != s[i - 1]:
			ans[i] = ans[i - 1]
			if s[i - 1] == '0':
				v2.remove(ans[i - 1])
				v1.append(ans[i])
			else:
				v1.remove(ans[i - 1])
				v2.append(ans[i])
		elif s[i] == '0':
			if v1:
				val = v1.pop()
				ans[i] = val
				v2.append(val)
			else:
				p += 1
				ans[i] = p
				v2.append(p)
		elif v2:
			val = v2.pop()
			ans[i] = val
			v1.append(val)
		else:
			p += 1
			ans[i] = p
			v1.append(p)
	print(p)
	print(*ans)


from collections import defaultdict, Counter
from math import log, ceil, floor

def solve():
	n = int(input())
	a = list(map(int, list(input())))
	d = {1: [-1], 0: [-1]}
	ans = [None for i in range(n)]
	cnt = 0
	for i in range(n):
		if a[i] == 0:
			if d[1][-1] > 0:
				ans[i] = d[1][-1]
				d[1].pop()
				d[0].append(ans[i])
			else:
				cnt += 1
				d[1].append(cnt)
				ans[i] = d[1][-1]
				d[1].pop()
				d[0].append(ans[i])
		elif d[0][-1] > 0:
			ans[i] = d[0][-1]
			d[0].pop()
			d[1].append(ans[i])
		else:
			cnt += 1
			d[0].append(cnt)
			ans[i] = d[0][-1]
			d[0].pop()
			d[1].append(ans[i])
	print(len(set(ans)))
	print(*ans)
t = 1
t = int(input())
for _ in range(t):
	solve()


from collections import defaultdict

def solution(s, n):
	g = 1
	A = [g]
	Q0 = []
	Q1 = []
	if s[0] == 0:
		Q0.append(1)
	else:
		Q1.append(1)
	for i in range(1, n):
		if s[i] == 1:
			if len(Q0) > 0:
				tg = Q0.pop()
				A.append(tg)
				Q1.append(tg)
			else:
				g += 1
				A.append(g)
				Q1.append(g)
		elif len(Q1) > 0:
			tg = Q1.pop()
			A.append(tg)
			Q0.append(tg)
		else:
			g += 1
			A.append(g)
			Q0.append(g)
	return (g, A)
t = int(input())
for _ in range(t):
	n = int(input())
	s = list(map(int, list(input())))
	(g, A) = solution(s, n)
	print(g)
	print(' '.join(map(str, A)))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	lst = {'0': [0, []], '1': [0, []]}
	mp = [0] * n
	ct = 0
	for i in range(n):
		if i == 0:
			lst[s[i]][0] = 1
			lst[s[i]][1].append(i)
			mp[i] = 1
			ct += 1
		elif s[i] == '1':
			if lst['0'][0] > 0:
				lst['0'][0] -= 1
				f = lst['0'][1][0]
				lst['0'][1].pop(0)
				mp[i] = mp[f]
				lst['1'][0] += 1
				lst['1'][1].append(i)
			else:
				ct += 1
				lst['1'][0] += 1
				lst['1'][1].append(i)
				mp[i] = ct
		elif lst['1'][0] > 0:
			lst['1'][0] -= 1
			f = lst['1'][1][0]
			lst['1'][1].pop(0)
			mp[i] = mp[f]
			lst['0'][0] += 1
			lst['0'][1].append(i)
		else:
			ct += 1
			lst['0'][0] += 1
			lst['0'][1].append(i)
			mp[i] = ct
	print(ct)
	for i in mp:
		print(i, end=' ')
	print()


import sys, io, os, time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for ii in range(int(input())):
	n = int(input())
	s = input()
	stack0 = []
	stack1 = []
	items = 0
	ans = [0] * n
	for (i, v) in enumerate(s):
		if v == '0':
			if len(stack1) == 0:
				items += 1
				ans[i] = items
				stack0.append(items)
			else:
				curr = stack1.pop()
				ans[i] = curr
				stack0.append(curr)
		elif len(stack0) == 0:
			items += 1
			ans[i] = items
			stack1.append(items)
		else:
			curr = stack0.pop()
			ans[i] = curr
			stack1.append(curr)
	print(items)
	print(*ans)


def main():
	from collections import deque
	Tquery = int(input())
	for _ in range(Tquery):
		N = int(input())
		S = input()
		ans = [-1] * N
		idx = [deque(), deque()]
		teamnum = 0
		for (i, s) in enumerate(S):
			if idx[int(s) ^ 1]:
				team = idx[int(s) ^ 1].popleft()
				ans[i] = team
				idx[int(s)].append(team)
			else:
				newteam = teamnum + 1
				ans[i] = newteam
				teamnum += 1
				idx[int(s)].append(newteam)
		print(teamnum)
		print(*ans)
main()


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	n1 = []
	n0 = []
	ans = []
	c1 = 0
	c0 = 0
	curr = 1
	for i in a:
		if i == '1':
			if c0 > 0:
				c1 += 1
				c0 -= 1
				ans.append(n0[-1])
				n1.append(n0[-1])
				n0.pop()
			else:
				c1 += 1
				ans.append(curr)
				n1.append(curr)
				curr += 1
		elif c1 > 0:
			c0 += 1
			c1 -= 1
			ans.append(n1[-1])
			n0.append(n1[-1])
			n1.pop()
		else:
			c0 += 1
			ans.append(curr)
			n0.append(curr)
			curr += 1
	print(c1 + c0)
	print(*ans)


for i in range(int(input())):
	n = int(input())
	s = input()
	k = 1
	a = [0] * n
	a[0] = 1
	stack_down = []
	stack_up = []
	for j in range(1, n):
		if s[j - 1:j + 1] in '101':
			pass
		elif stack_down and stack_down[-1] + s[j] in '101':
			k -= 1
			stack_down.pop()
			stack_up.append(s[j - 1])
		elif stack_up and stack_up[-1] + s[j] in '101':
			k += 1
			stack_up.pop()
			stack_down.append(s[j - 1])
		else:
			k += len(stack_up) + 1
			stack_down += [s[j - 1]] + stack_up
			stack_up = []
		a[j] = k
	print(max(a))
	for item in a:
		print(item, end=' ')


T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	need_zero = set()
	need_one = set()
	subs_so_far = 0
	ans = []
	for c in s:
		if c == '0':
			if len(need_zero) > 0:
				cur = need_zero.pop()
			else:
				subs_so_far += 1
				cur = subs_so_far
			ans.append(cur)
			need_one.add(cur)
		else:
			if len(need_one) > 0:
				cur = need_one.pop()
			else:
				subs_so_far += 1
				cur = subs_so_far
			ans.append(cur)
			need_zero.add(cur)
	print(subs_so_far)
	print(*ans)


numberOfCases = int(input())
i = 0
t = 0
while t < numberOfCases:
	numberOfSequences = int(input())
	sequence = input()
	sequence = [int(k) for k in sequence]
	uniqSeq = 0
	zeros = 0
	ones = 0
	numberOfSeqEndWithZero = []
	numberOfSeqEndWithOne = []
	for i in range(len(sequence)):
		if sequence[i] == 0:
			if len(numberOfSeqEndWithOne) != 0:
				s = numberOfSeqEndWithOne.pop()
				sequence[i] = s
				numberOfSeqEndWithZero.append(s)
			else:
				sequence[i] = uniqSeq + 1
				uniqSeq += 1
				numberOfSeqEndWithZero.append(uniqSeq)
		elif len(numberOfSeqEndWithZero) != 0:
			s = numberOfSeqEndWithZero.pop()
			sequence[i] = s
			numberOfSeqEndWithOne.append(s)
		else:
			sequence[i] = uniqSeq + 1
			uniqSeq += 1
			numberOfSeqEndWithOne.append(uniqSeq)
	print(uniqSeq)
	print(' '.join([str(k) for k in sequence]))
	t += 1


from sys import stdin, exit, setrecursionlimit
from collections import deque
input = stdin.readline
lmi = lambda : list(map(int, input().split()))
mi = lambda : map(int, input().split())
si = lambda : input().strip('\n')
ssi = lambda : input().strip('\n').split()
for _ in range(int(input())):
	n = int(input())
	s = si()
	ans = []
	arr = [[] for j in range(2)]
	nxt = 1
	for i in range(n):
		if s[i] == '1':
			if arr[0]:
				arr[1].append(arr[0].pop())
			else:
				arr[1].append(nxt)
				nxt += 1
			ans.append(arr[1][-1])
		else:
			if arr[1]:
				arr[0].append(arr[1].pop())
			else:
				arr[0].append(nxt)
				nxt += 1
			ans.append(arr[0][-1])
	print(max(ans))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	pos0 = []
	pos1 = []
	ans = [0] * n
	for i in range(n):
		newpos = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(newpos)
			else:
				newpos = pos1.pop()
				pos0.append(newpos)
		elif len(pos0) == 0:
			pos1.append(newpos)
		else:
			newpos = pos0.pop()
			pos1.append(newpos)
		ans[i] = newpos
	print(len(pos0) + len(pos1))
	print(*[x + 1 for x in ans])


import os
import sys
import queue
from io import BytesIO, IOBase

def main():
	t = int(input())
	while t:
		t -= 1
		n = int(input())
		s = input()
		(q0, q1) = (queue.Queue(), queue.Queue())
		belong = [0 for i in range(n)]
		tot = 0
		for i in range(n):
			if s[i] == '0':
				if not q1.empty():
					f = q1.get()
					belong[i] = f
					q0.put(f)
				else:
					tot += 1
					belong[i] = tot
					q0.put(tot)
			elif not q0.empty():
				f = q0.get()
				belong[i] = f
				q1.put(f)
			else:
				tot += 1
				belong[i] = tot
				q1.put(tot)
		print(tot)
		print(*belong)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	s = list(SI())
	count = 0
	mi = 0
	ans = []
	for i in range(0, n):
		if i != 0 and s[i] == s[i - 1]:
			if s[i] == '0':
				count += 1
			else:
				count -= 1
		ans.append(count)
		mi = min(mi, count)
	mi = 1 - mi
	for i in range(n):
		ans[i] += mi
	print(len(set(ans)))
	print(*ans)


t = int(input())
for case in range(t):
	n = int(input())
	s = input()
	zero = []
	one = []
	ans = []
	for i in range(n):
		newseq = len(zero) + len(one)
		if s[i] == '0':
			if not one:
				newseq += 1
				zero.append(newseq)
			else:
				zero.append(one.pop())
				newseq = zero[-1]
		elif not zero:
			newseq += 1
			one.append(newseq)
		else:
			one.append(zero.pop())
			newseq = one[-1]
		ans.append(newseq)
	print(len(zero) + len(one))
	for i in range(n):
		if i == n - 1:
			print(ans[i])
			break
		print(ans[i], end=' ')


for _ in range(int(input())):
	n = int(input())
	s = input()
	d = {0: [], 1: []}
	index = []
	count = 0
	for x in s:
		now = int(x)
		neg = int(not now)
		if len(d[neg]) > 0:
			ind = d[neg].pop()
			d[now].append(ind)
		else:
			count += 1
			d[now].append(count)
			ind = count
		index.append(ind)
	print(count)
	print(*index)


def mi():
	return map(int, input().split())

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def si():
	return input().split()
t = ii()
for _ in range(t):
	n = ii()
	a = input()
	dic = {}
	dic['0 0'] = 0
	dic['1 1'] = 0
	dic['1 0'] = 0
	dic['0 1'] = 0
	ans = [i for i in range(1, n + 1)]
	cnt = 0
	tmp1 = []
	tmp2 = []
	tmp3 = []
	tmp4 = []
	for i in range(n):
		if a[i] == '1':
			if dic.get('0 0') and dic['0 0'] > 0:
				dic['0 0'] -= 1
				ans[i] = tmp1.pop()
				dic['0 1'] += 1
				tmp4.append(ans[i])
			elif dic.get('1 0') and dic['1 0'] > 0:
				dic['1 1'] += 1
				dic['1 0'] -= 1
				ans[i] = tmp3.pop()
				tmp2.append(ans[i])
			else:
				dic['1 1'] += 1
				cnt += 1
				ans[i] = cnt
				tmp2.append(cnt)
		elif dic.get('1 1') and dic['1 1'] > 0:
			dic['1 1'] -= 1
			ans[i] = tmp2.pop()
			dic['1 0'] += 1
			tmp3.append(ans[i])
		elif dic.get('0 1') and dic['0 1'] > 0:
			dic['0 0'] += 1
			dic['0 1'] -= 1
			ans[i] = tmp4.pop()
			tmp1.append(ans[i])
		else:
			dic['0 0'] += 1
			cnt += 1
			tmp1.append(cnt)
			ans[i] = cnt
	print(cnt)
	for i in ans:
		print(i, end=' ')
	print()


tot = int(input().strip())
while tot > 0:
	n = int(input().strip())
	s = input().strip()
	p0 = []
	p1 = []
	a = [1 for _ in range(0, n)]
	cnt = 0
	for (i, x) in enumerate(s):
		if x == '0':
			if p1:
				a[i] = p1.pop()
				p0.append(a[i])
			else:
				cnt += 1
				a[i] = cnt
				p0.append(cnt)
		elif p0:
			a[i] = p0.pop()
			p1.append(a[i])
		else:
			cnt += 1
			a[i] = cnt
			p1.append(cnt)
	print(cnt)
	print(' '.join([str(x) for x in a]))
	tot -= 1


t = int(input())
R = lambda : map(int, input().split())
answersNumbers = []
answersBelonging = []
for i in range(0, t):
	n = int(input())
	a = input()
	maxNumber = 0
	onePossiblesSub = []
	zeroPossibleSub = []
	numbers = []
	for c in a:
		if c == '1':
			if not onePossiblesSub:
				maxNumber = maxNumber + 1
				onePossiblesSub.append(maxNumber)
			popped = onePossiblesSub.pop()
			numbers.append(popped)
			zeroPossibleSub.append(popped)
		if c == '0':
			if not zeroPossibleSub:
				maxNumber = maxNumber + 1
				zeroPossibleSub.append(maxNumber)
			popped = zeroPossibleSub.pop()
			onePossiblesSub.append(popped)
			numbers.append(popped)
	answersBelonging.append(numbers)
	answersNumbers.append(maxNumber)
for i in range(0, t):
	print(answersNumbers[i])
	for j in range(0, len(answersBelonging[i])):
		print(answersBelonging[i][j], sep='', end=' ')
	print()


import os
is_dev = 'vscode' in os.environ
if is_dev:
	inF = open('in.txt', 'r')
	outF = open('out.txt', 'w')

def ins(r):
	return list(map(int, r.split(' ')))

def input_():
	if is_dev:
		return inF.readline()[:-1]
	else:
		return input()

def print_(data):
	if is_dev:
		outF.write(str(data) + '\n')
	else:
		print(data)
for _ in range(int(input_())):
	n = int(input_())
	s = input_()
	sss = {'0': [], '1': []}
	sets = [s[0]]
	sss[s[0]].append(1)
	result = [1]
	result_counter = 1
	i = 1
	while i < len(s):
		not_s = '0' if s[i] == '1' else '1'
		if len(sss[not_s]) == 0:
			result_counter += 1
			sss[s[i]].append(result_counter)
			result.append(result_counter)
		else:
			nex = sss[not_s].pop()
			result.append(nex)
			sss[s[i]].append(nex)
		i += 1
	print_(result_counter)
	print_(' '.join(map(str, result)))
if is_dev:
	outF.close()

	def compare_file():
		print(open('out.txt', 'r').read() == open('outactual.txt', 'r').read())
	compare_file()


from sys import *
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input()
	d = [0] * n
	d[0] = 1
	cn = 1
	l0 = []
	l1 = []
	for i in range(1, n):
		if s[i] != s[i - 1]:
			d[i] = cn
		else:
			if s[i] == '1' and len(l0) > 0:
				d[i] = l0.pop()
				l1.append(d[i])
				continue
			elif s[i] == '0' and len(l1) > 0:
				d[i] = l1.pop()
				l0.append(d[i])
				continue
			m = cn
			cn += 1
			d[i] = cn
			if s[i - 1] == '1':
				l1.append(m)
			else:
				l0.append(m)
	stdout.write(str(cn) + '\n')
	for i in range(n):
		stdout.write(str(d[i]) + ' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	kol = []
	a = [0]
	b = 0
	for i in range(n):
		if s[i] == '1':
			b += 1
		else:
			b -= 1
		a.append(b)
	for i in range(n):
		kol.append(min(a[i], a[i + 1]))
	mn = 1000000000
	mx = 0
	for i in range(n):
		if kol[i] < mn:
			mn = kol[i]
	for i in range(n):
		if kol[i] - mn + 1 > mx:
			mx = kol[i] - mn + 1
	print(mx)
	for i in range(n):
		print(kol[i] - mn + 1, end=' ')
	print()


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a
from operator import add

def solve():
	n = int(inp())
	s = inp()
	zero = []
	one = []
	ans = []
	for i in range(n):
		k = len(zero) + len(one)
		if s[i] == '1':
			if zero:
				k = zero.pop()
				one.append(k)
			else:
				one.append(k)
		elif one:
			k = one.pop()
			zero.append(k)
		else:
			zero.append(k)
		ans.append(k + 1)
	print(len(zero) + len(one))
	print(*ans)
testcase(int(inp()))


for _ in range(int(input())):
	n = int(input())
	s = input()
	sss0 = []
	sss1 = []
	if s[0] == '0':
		sss0.append(1)
	else:
		sss1.append(1)
	result = [1]
	result_counter = 1
	i = 1
	while i < n:
		if s[i] == '0':
			if len(sss1) == 0:
				result_counter += 1
				sss0.append(result_counter)
				result.append(result_counter)
			else:
				nex = sss1.pop()
				result.append(nex)
				sss0.append(nex)
		elif len(sss0) == 0:
			result_counter += 1
			sss1.append(result_counter)
			result.append(result_counter)
		else:
			nex = sss0.pop()
			result.append(nex)
			sss1.append(nex)
		i += 1
	print(result_counter)
	print(' '.join(map(str, result)))


t = int(input())
while t != 0:
	n = int(input())
	s = input()
	o_list = []
	z_list = []
	for i in range(len(s)):
		if s[i] == '0':
			if len(o_list) > 0:
				o_list[-1].append(i)
				temp = o_list.pop()
				z_list.append(temp)
			else:
				z_list.append([i])
		elif len(z_list) > 0:
			z_list[-1].append(i)
			temp = z_list.pop()
			o_list.append(temp)
		else:
			o_list.append([i])
	d = {}
	for i in range(n):
		d[i] = -1
	k = 0
	for i in range(len(o_list)):
		for j in range(len(o_list[i])):
			d[o_list[i][j]] = i + 1
		k += 1
	for i in range(len(z_list)):
		for j in range(len(z_list[i])):
			d[z_list[i][j]] = i + 1 + k
	print(len(o_list) + len(z_list))
	for i in d.keys():
		print(d[i], end=' ')
	print()
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	result = [0] * n
	ones = []
	zeroes = []
	current = 1
	for i in range(n):
		if s[i] == '0':
			if len(zeroes) == 0:
				ones.append(current)
				result[i] = current
				current += 1
			else:
				x = zeroes.pop()
				result[i] = x
				ones.append(x)
		elif len(ones) == 0:
			zeroes.append(current)
			result[i] = current
			current += 1
		else:
			x = ones.pop()
			result[i] = x
			zeroes.append(x)
	print(current - 1)
	print(*result)


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_right(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		n = I()
		l = list(input())
		(d0, d1) = (deque(), deque())
		(ma0, ma1) = (0, 0)
		ans = []
		for x in range(n):
			if l[x] == '1':
				if len(d0) > 0:
					ans.append(ans[d0[-1]])
					d0.pop()
				else:
					ma1 = max(ma1, ma0)
					ma1 += 1
					ans.append(ma1)
				d1.append(x)
			else:
				if len(d1) > 0:
					ans.append(ans[d1[-1]])
					d1.pop()
				else:
					ma0 = max(ma0, ma1)
					ma0 += 1
					ans.append(ma0)
				d0.append(x)
		print(max(ma0, ma1))
		print(*ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	ar = input().rstrip()
	ans = []
	nt = set()
	zt = set()
	ct = 2
	if ar[0] == '0':
		nt.add(1)
	else:
		zt.add(1)
	ans.append(1)
	for i in range(1, n):
		if ar[i] == '0':
			if len(zt) != 0:
				y = zt.pop()
				nt.add(y)
				ans.append(y)
			else:
				nt.add(ct)
				ans.append(ct)
				ct += 1
		elif len(nt) != 0:
			y = nt.pop()
			zt.add(y)
			ans.append(y)
		else:
			zt.add(ct)
			ans.append(ct)
			ct += 1
	print(max(ans))
	print(*ans)


from collections import defaultdict
from collections import Counter
t = int(input())
for q in range(0, t):
	n = int(input())
	a = input()
	ans = []
	count = 0
	zeros = []
	ones = []
	for i in range(0, n):
		if a[i] == '1':
			if len(zeros) == 0:
				ones.append(count + 1)
				ans.append(count + 1)
				count += 1
			else:
				ans.append(zeros[len(zeros) - 1])
				ones.append(zeros[len(zeros) - 1])
				zeros.pop(len(zeros) - 1)
		elif len(ones) == 0:
			zeros.append(count + 1)
			ans.append(count + 1)
			count += 1
		else:
			ans.append(ones[len(ones) - 1])
			zeros.append(ones[len(ones) - 1])
			ones.pop(len(ones) - 1)
	print(count)
	print(*ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	stdin.readline()
	s = stdin.readline().strip()
	one_stack = []
	z_stack = []
	count = 0
	res = []
	for char in s:
		if char == '1':
			if len(z_stack) == 0:
				count += 1
				res.append(count)
				one_stack.append(count)
			else:
				t = z_stack.pop()
				res.append(t)
				one_stack.append(t)
		elif len(one_stack) == 0:
			count += 1
			res.append(count)
			z_stack.append(count)
		else:
			t = one_stack.pop()
			res.append(t)
			z_stack.append(t)
	print(count)
	print(*res)


import heapq as hp
alt = lambda arr, x: '1' if arr[x] == '0' else '0'
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = [0] * n
	g = 1
	b[0] = g
	c = {'0': [], '1': []}
	hp.heappush(c[alt(a, 0)], g)
	for i in range(1, n):
		idx = hp.heappop(c[a[i]]) if c[a[i]] else -1
		if idx != -1:
			b[i] = idx
			hp.heappush(c[alt(a, i)], idx)
		else:
			g += 1
			hp.heappush(c[alt(a, i)], g)
			b[i] = g
	print(g)
	print(*b)


from collections import defaultdict

def main():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		ans = [0] * n
		count = 0
		d = defaultdict(list)
		for i in range(n):
			if s[i] == '0':
				if not d[1]:
					count += 1
					d[0].append(count)
					ans[i] = count
				else:
					p = d[1].pop()
					ans[i] = p
					d[0].append(p)
			elif not d[0]:
				count += 1
				d[1].append(count)
				ans[i] = count
			else:
				p = d[0].pop()
				ans[i] = p
				d[1].append(p)
		print(count)
		print(*ans)
main()


from collections import deque

def findBinSS(s):
	endsWith0 = deque()
	endsWith1 = deque()
	count = 0
	N = len(s)
	subseq = [0] * N
	for i in range(N):
		if s[i] == '0' and len(endsWith1) > 0:
			curr = endsWith1.popleft()
			endsWith0.append(curr)
			subseq[i] = curr
		elif s[i] == '0':
			count += 1
			endsWith0.append(count)
			subseq[i] = count
		elif s[i] == '1' and len(endsWith0) > 0:
			curr = endsWith0.popleft()
			endsWith1.append(curr)
			subseq[i] = curr
		else:
			count += 1
			endsWith1.append(count)
			subseq[i] = count
	return (count, subseq)
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	(count, subseq) = findBinSS(s)
	print(count)
	print(*subseq)


t = int(input())
for test_case in range(t):
	end_one = []
	end_zero = []
	col = []
	ptr = 0
	n = int(input())
	s = input()
	for i in range(n):
		if s[i] == '1':
			if len(end_zero) == 0:
				ptr += 1
				end_one.append(ptr)
				col.append(ptr)
			else:
				c = end_zero.pop(len(end_zero) - 1)
				end_one.append(c)
				col.append(c)
		elif len(end_one) == 0:
			ptr += 1
			end_zero.append(ptr)
			col.append(ptr)
		else:
			c = end_one.pop(len(end_one) - 1)
			end_zero.append(c)
			col.append(c)
	print(ptr)
	for i in col:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = input()
	cnt = 1
	end = {0: [-1], 1: [-1]}
	end[int(s[0])].append(0)
	ans = [cnt]
	for i in range(1, n):
		is_val = int(s[i])
		not_val = is_val ^ 1
		if end[not_val][-1] != -1:
			end[is_val].append(end[not_val].pop())
			ans.append(ans[end[is_val][-1]])
		else:
			end[is_val].append(i)
			ans.append(cnt + 1)
			cnt += 1
	print(cnt)
	print(*ans)


from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math
rl = lambda : stdin.readline()
rll = lambda : stdin.readline().split()
rli = lambda : map(int, stdin.readline().split())
rlf = lambda : map(float, stdin.readline().split())
(INF, NINF) = (float('inf'), float('-inf'))
MOD = 10 ** 9 + 7

def main():
	T = int(rl())
	for _ in range(T):
		n = int(rl())
		A = [int(x) for x in list(rll()[0])]
		cnt = 1
		ans = [0 for _ in range(n)]
		(last0, last1) = ([], [])
		for (i, b) in enumerate(A):
			if b == 1:
				if last0:
					ans[i] = ans[last0.pop()]
				else:
					ans[i] = cnt
					cnt += 1
				last1.append(i)
			else:
				if last1:
					ans[i] = ans[last1.pop()]
				else:
					ans[i] = cnt
					cnt += 1
				last0.append(i)
		print(cnt - 1)
		print(' '.join((str(x) for x in ans)))
	stdout.close()
main()


import sys

def main():
	res = ''
	input = sys.stdin.readline
	print = sys.stdout.write
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		zeros = []
		k_zeros = 0
		ones = []
		k_ones = 0
		nums = []
		k = 0
		for i in range(n):
			if s[i] == '1':
				k_ones += 1
				if k_zeros != 0:
					k_zeros -= 1
					nums.append(str(zeros[-1]))
					ones.append(zeros[-1])
					del zeros[-1]
				else:
					k += 1
					ones.append(k)
					nums.append(str(k))
			else:
				k_zeros += 1
				if k_ones != 0:
					k_ones -= 1
					nums.append(str(ones[-1]))
					zeros.append(ones[-1])
					del ones[-1]
				else:
					k += 1
					zeros.append(k)
					nums.append(str(k))
		res += str(k) + '\n' + ' '.join(nums) + '\n'
	print(res)
main()


for _ in range(int(input())):
	n = int(input())
	(a, b, ans) = ([], [], [])
	for i in input():
		if i == '0':
			if b:
				a.append(b.pop())
			else:
				a.append(len(a) + len(b) + 1)
			ans.append(a[-1])
		else:
			if a:
				b.append(a.pop())
			else:
				b.append(len(a) + len(b) + 1)
			ans.append(b[-1])
	print(max(ans))
	print(*ans)


from math import log2

def readGenerator():
	while True:
		tokens = input().split(' ')
		for t in tokens:
			yield t
reader = readGenerator()

def readWord():
	return next(reader)

def readInt():
	return int(next(reader))

def readFloat():
	return float(next(reader))

def readLine():
	return input()

def solve(n):
	return n
t = readInt()
for _ in range(0, t):
	n = readInt()
	s = readWord()
	res = [[], []]
	for i in range(0, len(s)):
		if s[i] == '0':
			if len(res[1]) == 0:
				res[0].append([i])
				continue
		if s[i] == '1':
			if len(res[0]) == 0:
				res[1].append([i])
				continue
		p = (ord(s[i]) - ord('0') + 1) % 2
		move = res[p].pop(len(res[p]) - 1)
		move.append(i)
		res[(p + 1) % 2].append(move)
	ans = [*res[0], *res[1]]
	res = [0] * n
	print(len(ans))
	for i in range(0, len(ans)):
		for v in ans[i]:
			res[v] = i + 1
	print(' '.join(map(str, res)))


def split_to_subsequences(s):
	seqs = {0: set(), 1: set()}
	seqs_count = 0
	result = []
	for ch in map(int, s):
		if seqs[1 - ch]:
			cur_seq = seqs[1 - ch].pop()
			result.append(cur_seq)
			seqs[ch].add(cur_seq)
		else:
			seqs_count += 1
			result.append(seqs_count)
			seqs[ch].add(seqs_count)
	return (seqs_count, result)

def main():
	for _ in range(int(input())):
		input()
		(seqs_count, result) = split_to_subsequences(input())
		print(seqs_count)
		print(' '.join([str(item) for item in result]))
main()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	n = int(input())
	s = input()
	ezero = []
	eone = []
	t = 0
	ans = [0] * n
	for i in range(n):
		if int(s[i]) == 0:
			if eone == []:
				t += 1
				ezero.append(t)
				ans[i] = t
			else:
				w = eone.pop()
				ezero.append(w)
				ans[i] = w
		elif ezero == []:
			t += 1
			eone.append(t)
			ans[i] = t
		else:
			w = ezero.pop()
			eone.append(w)
			ans[i] = w
	print(t)
	print(*ans)


import sys, math
from collections import Counter, deque, defaultdict
input = sys.stdin.readline
L = lambda : list(map(int, input().split()))
M = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input()
C = lambda : input().strip().split()
mod = 1000000007

def pl(a):
	print(' '.join(list(map(str, a))))

def solve():
	n = I()
	s = S()
	x = s[0]
	l = []
	v = 1
	for i in range(n):
		if s[i] == x:
			l += [v]
			v += 1
		if s[i] != x:
			v -= 1
			l += [v]
	m = min(l)
	if m < 1:
		for i in range(n):
			l[i] = l[i] + 1 - m
	print(max(l))
	pl(l)
for _ in range(I()):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = [0] * n
	max_elem = 0
	want_indices = [[], []]
	for (i, d) in enumerate(map(int, s)):
		if not want_indices[d]:
			max_elem += 1
			ans[i] = max_elem
			want_indices[1 - d].append(max_elem)
		else:
			index = want_indices[d].pop()
			ans[i] = index
			want_indices[1 - d].append(index)
	print(max_elem)
	print(*ans, sep=' ')


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())
import random

class TreapMultiSet(object):
	root = 0
	size = 0

	def __init__(self, data=None):
		if data:
			data = sorted(data)
			self.root = treap_builder(data)
			self.size = len(data)

	def add(self, key):
		self.root = treap_insert(self.root, key)
		self.size += 1

	def remove(self, key):
		self.root = treap_erase(self.root, key)
		self.size -= 1

	def discard(self, key):
		try:
			self.remove(key)
		except KeyError:
			pass

	def ceiling(self, key):
		x = treap_ceiling(self.root, key)
		return treap_keys[x] if x else None

	def higher(self, key):
		x = treap_higher(self.root, key)
		return treap_keys[x] if x else None

	def floor(self, key):
		x = treap_floor(self.root, key)
		return treap_keys[x] if x else None

	def lower(self, key):
		x = treap_lower(self.root, key)
		return treap_keys[x] if x else None

	def max(self):
		return treap_keys[treap_max(self.root)]

	def min(self):
		return treap_keys[treap_min(self.root)]

	def __len__(self):
		return self.size

	def __nonzero__(self):
		return bool(self.root)
	__bool__ = __nonzero__

	def __contains__(self, key):
		return self.floor(key) == key

	def __repr__(self):
		return 'TreapMultiSet({})'.format(list(self))

	def __iter__(self):
		if not self.root:
			return iter([])
		out = []
		stack = [self.root]
		while stack:
			node = stack.pop()
			if node > 0:
				if right_child[node]:
					stack.append(right_child[node])
				stack.append(~node)
				if left_child[node]:
					stack.append(left_child[node])
			else:
				out.append(treap_keys[~node])
		return iter(out)
left_child = [0]
right_child = [0]
treap_keys = [0]
treap_prior = [0.0]

def treap_builder(sorted_data):

	def build(begin, end):
		if begin == end:
			return 0
		mid = (begin + end) // 2
		root = treap_create_node(sorted_data[mid])
		left_child[root] = build(begin, mid)
		right_child[root] = build(mid + 1, end)
		ind = root
		while True:
			lc = left_child[ind]
			rc = right_child[ind]
			if lc and treap_prior[lc] > treap_prior[ind]:
				if rc and treap_prior[rc] > treap_prior[rc]:
					(treap_prior[ind], treap_prior[rc]) = (treap_prior[rc], treap_prior[ind])
					ind = rc
				else:
					(treap_prior[ind], treap_prior[lc]) = (treap_prior[lc], treap_prior[ind])
					ind = lc
			elif rc and treap_prior[rc] > treap_prior[ind]:
				(treap_prior[ind], treap_prior[rc]) = (treap_prior[rc], treap_prior[ind])
				ind = rc
			else:
				break
		return root
	return build(0, len(sorted_data))

def treap_create_node(key):
	treap_keys.append(key)
	treap_prior.append(random.random())
	left_child.append(0)
	right_child.append(0)
	return len(treap_keys) - 1

def treap_split(root, key):
	left_pos = right_pos = 0
	while root:
		if key < treap_keys[root]:
			left_child[right_pos] = right_pos = root
			root = left_child[root]
		else:
			right_child[left_pos] = left_pos = root
			root = right_child[root]
	(left, right) = (right_child[0], left_child[0])
	right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
	return (left, right)

def treap_merge(left, right):
	(where, pos) = (left_child, 0)
	while left and right:
		if treap_prior[left] > treap_prior[right]:
			where[pos] = pos = left
			where = right_child
			left = right_child[left]
		else:
			where[pos] = pos = right
			where = left_child
			right = left_child[right]
	where[pos] = left or right
	node = left_child[0]
	left_child[0] = 0
	return node

def treap_insert(root, key):
	if not root:
		return treap_create_node(key)
	(left, right) = treap_split(root, key)
	return treap_merge(treap_merge(left, treap_create_node(key)), right)

def treap_insert_unique(root, key):
	if not root:
		return (treap_create_node(key), False)
	(left, right) = treap_split(root, key)
	if left and treap_keys[left] == key:
		return (treap_merge(left, right), True)
	return (treap_merge(treap_merge(left, treap_create_node(key)), right), False)

def treap_erase(root, key):
	if not root:
		raise KeyError(key)
	if treap_keys[root] == key:
		return treap_merge(left_child[root], right_child[root])
	node = root
	while root and treap_keys[root] != key:
		parent = root
		root = left_child[root] if key < treap_keys[root] else right_child[root]
	if not root:
		raise KeyError(key)
	if root == left_child[parent]:
		left_child[parent] = treap_merge(left_child[root], right_child[root])
	else:
		right_child[parent] = treap_merge(left_child[root], right_child[root])
	return node

def treap_ceiling(root, key):
	while root and treap_keys[root] < key:
		root = right_child[root]
	if not root:
		return 0
	min_node = root
	min_key = treap_keys[root]
	while root:
		if treap_keys[root] < key:
			root = right_child[root]
		else:
			if treap_keys[root] < min_key:
				min_key = treap_keys[root]
				min_node = root
			root = left_child[root]
	return min_node

def treap_higher(root, key):
	while root and treap_keys[root] <= key:
		root = right_child[root]
	if not root:
		return 0
	min_node = root
	min_key = treap_keys[root]
	while root:
		if treap_keys[root] <= key:
			root = right_child[root]
		else:
			if treap_keys[root] < min_key:
				min_key = treap_keys[root]
				min_node = root
			root = left_child[root]
	return min_node

def treap_floor(root, key):
	while root and treap_keys[root] > key:
		root = left_child[root]
	if not root:
		return 0
	max_node = root
	max_key = treap_keys[root]
	while root:
		if treap_keys[root] > key:
			root = left_child[root]
		else:
			if treap_keys[root] > max_key:
				max_key = treap_keys[root]
				max_node = root
			root = right_child[root]
	return max_node

def treap_lower(root, key):
	while root and treap_keys[root] >= key:
		root = left_child[root]
	if not root:
		return 0
	max_node = root
	max_key = treap_keys[root]
	while root:
		if treap_keys[root] >= key:
			root = left_child[root]
		else:
			if treap_keys[root] > max_key:
				max_key = treap_keys[root]
				max_node = root
			root = right_child[root]
	return max_node

def treap_min(root):
	if not root:
		raise ValueError('min on empty treap')
	while left_child[root]:
		root = left_child[root]
	return root

def treap_max(root):
	if not root:
		raise ValueError('max on empty treap')
	while right_child[root]:
		root = right_child[root]
	return root

def get_next():
	global z_start, zero, one, idx
	if z_start:
		return one.higher(idx)
	return zero.higher(idx)
for case in range(1, itg() + 1):
	n = itg()
	s = inp()
	zero = []
	one = []
	for i in range(n):
		if s[i] == '0':
			zero.append(i)
		else:
			one.append(i)
	zero = TreapMultiSet(zero)
	one = TreapMultiSet(one)
	ans = [0] * n
	t = 1
	while len(zero) != 0 or len(one) != 0:
		if len(one) == 0:
			z_start = True
		elif len(zero) == 0:
			z_start = False
		else:
			z_start = zero.min() < one.min()
		if z_start:
			idx = zero.min()
			zero.remove(idx)
		else:
			idx = one.min()
			one.remove(idx)
		ans[idx] = t
		idx = get_next()
		while idx is not None:
			if z_start:
				one.remove(idx)
			else:
				zero.remove(idx)
			ans[idx] = t
			z_start ^= 1
			idx = get_next()
		t += 1
	print(t - 1)
	print(*ans)


import sys, math, heapq, copy
from collections import defaultdict, deque
from bisect import bisect_left, bisect_right
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	zeros = []
	ones = []
	m1 = 0
	m2 = 0
	ref = [-1] * n
	for i in range(n - 1, -1, -1):
		if s[i] == '0':
			if m2 > 0:
				ref[i] = ones[m2 - 1]
				ones.pop()
				m2 -= 1
			zeros.append(i)
			m1 += 1
		else:
			if m1 > 0:
				ref[i] = zeros[m1 - 1]
				zeros.pop()
				m1 -= 1
			ones.append(i)
			m2 += 1
	ans = 0
	visited = [False] * n
	res = [0] * n
	for i in range(n):
		if ref[i] == -1 and visited[i] == False:
			visited[i] = True
			ans += 1
			res[i] = ans
		elif visited[i] == False:
			ans += 1
			j = i
			res[j] = ans
			visited[j] = True
			while ref[j] != -1:
				j = ref[j]
				visited[j] = True
				res[j] = ans
	print(ans)
	for i in res:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = [0 for x in range(n)]
	l_0 = []
	l_1 = []
	counter = 0
	for i in range(n):
		if s[i] == '0':
			if len(l_1) == 0:
				counter += 1
				l_0.append(counter)
				ans[i] = counter
			else:
				l_0.append(l_1[len(l_1) - 1])
				l_1.pop()
				ans[i] = l_0[len(l_0) - 1]
		elif len(l_0) == 0:
			counter += 1
			l_1.append(counter)
			ans[i] = counter
		else:
			l_1.append(l_0[len(l_0) - 1])
			l_0.pop()
			ans[i] = l_1[len(l_1) - 1]
	print(counter)
	for i in range(n):
		print(ans[i], end=' ')
	print()


def minSubs(s):
	zero = []
	one = []
	pos = [1]
	d = {'0': 0, '1': 0}
	d[s[0]] += 1
	if s[0] == '0':
		zero = [1]
	else:
		one = [1]
	for i in range(1, len(s)):
		if s[i] == '0':
			if d['1'] > 0:
				d['1'] -= 1
				d['0'] += 1
				pos.append(one[-1])
				zero.append(one[-1])
				one.remove(one[-1])
			else:
				d['0'] += 1
				pos.append(max(zero[0], zero[-1]) + 1)
				zero.append(pos[-1])
		elif d['0'] > 0:
			d['0'] -= 1
			d['1'] += 1
			pos.append(zero[-1])
			one.append(zero[-1])
			zero.remove(zero[-1])
		else:
			d['1'] += 1
			pos.append(max(one[0], one[-1]) + 1)
			one.append(pos[-1])
	return (d['0'] + d['1'], pos)
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(a1, a2) = minSubs(s)
	print(a1)
	print(' '.join(map(str, a2)))


from collections import deque
for _ in range(int(input())):
	a = int(input())
	s = input()
	s0 = deque()
	s1 = deque()
	ans = []
	ln = 0
	for i in range(a):
		if s[i] == '1':
			if not s0:
				s1.append(i)
				ln += 1
				ans.append(ln)
			else:
				q = s0.popleft()
				ans.append(ans[q])
				s1.append(i)
		elif not s1:
			s0.append(i)
			ln += 1
			ans.append(ln)
		else:
			q = s1.popleft()
			ans.append(ans[q])
			s0.append(i)
	print(ln)
	print(*ans)


from heapq import *
for _ in range(int(input())):
	r = []
	f = []
	heapify(r)
	heapify(f)
	q = 0
	w = 0
	n = int(input())
	l = [0] * n
	k = 1
	a = input()
	for i in range(n):
		if int(a[i]) == 1:
			if f:
				l[i] = heappop(f)
				heappush(r, l[i])
			else:
				q += 1
				heappush(r, q)
				l[i] = q
		elif r:
			l[i] = heappop(r)
			heappush(f, l[i])
		else:
			q += 1
			heappush(f, q)
			l[i] = q
	print(len(set(l)))
	print(*l)


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		s = input()
		ans = []
		d = defaultdict(set)
		ct = 1
		res = 1
		for i in range(n - 1):
			if s[i] == s[i + 1]:
				v = '1' if s[i + 1] == '0' else '0'
				d[s[i]].add(ct)
				ans.append(ct)
				if v in d:
					pos = -1
					for i in d[v]:
						pos = i
						break
					d[v].remove(pos)
					if len(d[v]) == 0:
						del d[v]
					ct = pos
				else:
					res += 1
					ct = res
			else:
				ans.append(ct)
		ans.append(ct)
		print(res)
		for i in ans:
			print(i, end=' ')
		print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right
from collections import deque

def L():
	return list(map(int, stdin.readline().split()))

def In():
	return map(int, stdin.readline().split())

def I():
	return int(stdin.readline())
P = 1000000007

def main():
	for t in range(I()):
		n = I()
		s = input()
		lis = [0 for i in range(n)]
		st1 = deque()
		st0 = deque()
		val = 0
		for i in range(n):
			if int(s[i]) == 1:
				if st0:
					x = st0.popleft()
					lis[i] = x
					st1.append(x)
				else:
					val += 1
					lis[i] = val
					st1.append(val)
			elif st1:
				x = st1.popleft()
				lis[i] = x
				st0.append(x)
			else:
				val += 1
				lis[i] = val
				st0.append(val)
		print(max(lis))
		print(*lis)
main()


for t in range(int(input())):
	index = 1
	ans = []
	n = input()
	zero = []
	one = []
	for b in input():
		if b == '0':
			if len(one) == 0:
				zero.append(index)
				ans.append(index)
				index += 1
			else:
				zero.append(one[-1])
				ans.append(one.pop())
		elif len(zero) == 0:
			one.append(index)
			ans.append(index)
			index += 1
		else:
			one.append(zero[-1])
			ans.append(zero.pop())
	print(index - 1)
	print(*ans)


import math
import heapq
import sys
import bisect
from collections import deque
import time
input = sys.stdin.readline
mod = 10 ** 9 + 7

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def hash(x, y, n):
	return x + n * (y - 1)
for _ in range(inp()):
	n = inp()
	l = insr()
	out = []
	d = {'0': [], '1': []}
	if l[0] == '0':
		out.append(1)
		d['1'].append(1)
	else:
		out.append(1)
		d['0'].append(1)
	m = 1
	for i in range(1, n):
		if l[i] == '0':
			if len(d['0']) == 0:
				out.append(m + 1)
				m += 1
				d['1'].append(m)
			else:
				out.append(d['0'][-1])
				d['0'].pop()
				d['1'].append(out[-1])
		elif len(d['1']) == 0:
			out.append(m + 1)
			m += 1
			d['0'].append(m)
		else:
			out.append(d['1'][-1])
			d['1'].pop()
			d['0'].append(out[-1])
	print(max(out))
	print(*out)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = [0] * n
	(pos0, pos1) = ([], [])
	for i in range(n):
		newpos = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(newpos)
			else:
				newpos = pos1[len(pos1) - 1]
				pos1.pop()
				pos0.append(newpos)
		elif len(pos0) == 0:
			pos1.append(newpos)
		else:
			newpos = pos0[len(pos0) - 1]
			pos0.pop()
			pos1.append(newpos)
		ans[i] = newpos
	print(len(pos0) + len(pos1))
	for i in ans:
		print(i + 1, end=' ')
	print()


import copy
from bisect import bisect_right as bl
for _ in range(int(input())):
	n = int(input())
	s = input()
	one = []
	zero = []
	ans = []
	cnt = 0
	d = {1: [], 0: []}
	for i in range(n):
		no = int(s[i])
		invNo = 1 - no
		if len(d[invNo]) == 0:
			cnt += 1
			ans.append(cnt)
			d[no].append(i)
		else:
			ans.append(ans[d[invNo][0]])
			del d[invNo][0]
			d[no].append(i)
	print(cnt)
	for i in ans:
		print(i, end=' ')
	print('')


n = int(input())
for i in range(n):
	l = int(input())
	s = str(input())
	(num0, num1) = (0, 0)
	grp = []
	for c in s:
		if c == '1':
			if num0 > 0:
				grp.append(num0)
				num0 -= 1
				num1 += 1
			else:
				grp.append(num0 + num1 + 1)
				num1 += 1
		if c == '0':
			if num1 > 0:
				grp.append(num0 + 1)
				num1 -= 1
				num0 += 1
			else:
				grp.append(num0 + 1)
				num0 += 1
	print(num0 + num1)
	for z in grp:
		print(z, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = []
	zstack = []
	ostack = []
	pans = 0
	curr = 0
	for i in range(n):
		if s[i] == '0':
			if len(ostack) == 0:
				zstack.append(curr)
				ans.append(curr + 1)
				curr += 1
			else:
				noice = ostack.pop()
				ans.append(noice + 1)
				zstack.append(noice)
		elif len(zstack) == 0:
			ostack.append(curr)
			ans.append(curr + 1)
			curr += 1
		else:
			noice = zstack.pop()
			ans.append(noice + 1)
			ostack.append(noice)
		pans = max([pans, len(zstack), len(ostack)])
	print(pans)
	print(' '.join(list(map(str, ans))))


def func(s):
	find_0 = []
	find_1 = []
	latest = 1
	output = []
	if s[0] == '0':
		find_1.append(latest)
	else:
		find_0.append(latest)
	latest += 1
	output.append(1)
	for i in s[1:]:
		if i == '0':
			if len(find_0) == 0:
				find_1.append(latest)
				output.append(latest)
				latest += 1
			else:
				x = find_0[-1]
				output.append(x)
				find_1.append(x)
				find_0.pop()
		elif len(find_1) == 0:
			find_0.append(latest)
			output.append(latest)
			latest += 1
		else:
			x = find_1[-1]
			output.append(x)
			find_0.append(x)
			find_1.pop()
	return str(latest - 1) + '\n' + ' '.join(list(map(str, output)))

def main():
	for i in range(int(input())):
		input()
		print(func(input()))
main()


def solve(s):
	zero = []
	one = []
	res = []
	cnt = 1
	for i in s:
		if i == '1':
			if len(zero) > 0:
				res.append(zero[-1])
				one.append(zero.pop())
			else:
				res.append(cnt)
				one.append(cnt)
				cnt += 1
		elif len(one) > 0:
			res.append(one[-1])
			zero.append(one.pop())
		else:
			res.append(cnt)
			zero.append(cnt)
			cnt += 1
	res.append(cnt - 1)
	return res
T = int(input())
while T > 0:
	T -= 1
	n = int(input())
	s = str(input())
	res = solve(s)
	print(res[-1])
	for i in range(0, len(res) - 1):
		print(res[i], end=' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	ans = 1
	cnt = 1
	f_el = a[0]
	result = [0] * (n + 1)
	result[0] = 1
	for j in range(1, n):
		if a[j] == f_el:
			if cnt == ans:
				ans += 1
			cnt += 1
			result[j] = cnt
		else:
			result[j] = cnt
			cnt -= 1
			if cnt < 1:
				cnt = ans
				f_el = a[j]
	print(ans)
	print(*result[:n])


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 0 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	n = I()
	grp = 1
	d = {'1': [], '0': []}
	v = []
	for i in S():
		if not d[i]:
			v += (grp,)
			if i == '1':
				d['0'] += (grp,)
			else:
				d['1'] += (grp,)
			grp += 1
		else:
			val = d[i].pop()
			if i == '1':
				d['0'] += (val,)
			else:
				d['1'] += (val,)
			v += (val,)
	print(max(v))
	print(*v)


import sys, collections
from heapq import heappop, heappush
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))
t = inp()
for _ in range(t):
	n = inp()
	s = input()
	pq0 = []
	pq1 = []
	ln0 = ln1 = 0
	mx = 0
	res = [-1] * n
	for (i, x) in enumerate(s):
		if x == '0':
			if ln1 == 0:
				mx += 1
				heappush(pq1, mx)
				ln1 += 1
			now = heappop(pq1)
			heappush(pq0, now)
			res[i] = now
			ln1 -= 1
			ln0 += 1
		else:
			if ln0 == 0:
				mx += 1
				heappush(pq0, mx)
				ln0 += 1
			now = heappop(pq0)
			heappush(pq1, now)
			res[i] = now
			ln0 -= 1
			ln1 += 1
	print(mx)
	print(*res)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	d = {0: set(), 1: set()}
	ans = []
	k = 0
	for i in range(n):
		if s[i] == '0':
			if not d[1]:
				k += 1
				d[0].add(k)
				ans.append(k)
			else:
				x = d[1].pop()
				ans.append(x)
				d[0].add(x)
		elif not d[0]:
			k += 1
			d[1].add(k)
			ans.append(k)
		else:
			x = d[0].pop()
			ans.append(x)
			d[1].add(x)
	print(max(ans))
	print(*ans)


import sys
from math import sqrt, gcd, ceil, log
from collections import defaultdict, Counter, deque
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))

def main():
	ans_ = []
	for _ in range(int(input())):
		n = int(input())
		s = input().strip()
		stk = defaultdict(list)
		ans_list = [0] * n
		ans_list[0] = 1
		stk[s[0]].append(1)
		opp = {'0': '1', '1': '0'}
		c = 1
		for i in range(1, n):
			if s[i] == s[i - 1]:
				if stk[opp[s[i]]]:
					v = stk[opp[s[i]]].pop()
					ans_list[i] = v
					stk[s[i]].append(v)
				else:
					c += 1
					ans_list[i] = c
					stk[s[i]].append(c)
			else:
				ans_list[i] = ans_list[i - 1]
				stk[s[i]].append(stk[s[i - 1]].pop())
		ans_.append(str(c) + '\n' + ' '.join(map(str, ans_list)))
	print('\n'.join(ans_))
main()


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	s = list(inp())
	zeroes = []
	ones = []
	ans = []
	for i in range(len(s)):
		pos = len(zeroes) + len(ones)
		if s[i] == '0':
			if not ones:
				zeroes.append(pos)
			else:
				pos = ones.pop()
				zeroes.append(pos)
		elif not zeroes:
			ones.append(pos)
		else:
			pos = zeroes.pop()
			ones.append(pos)
		ans.append(pos + 1)
	print(len(zeroes) + len(ones))
	print(*ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import deque

def gift():
	for _ in range(t):
		n = int(input())
		arry = input()
		zstk = deque()
		ostk = deque()
		ans = [0] * n
		(len0, len1) = (0, 0)
		if arry[0] == '1':
			ostk.append(1)
			len1 += 1
		else:
			zstk.append(1)
			len0 += 1
		ans[0] = 1
		curr = 1
		for i in range(1, n):
			if arry[i] == '1':
				if len0 == 0:
					curr += 1
					len1 += 1
					ostk.append(curr)
					ans[i] = curr
				else:
					ele = zstk.popleft()
					len0 -= 1
					len1 += 1
					ostk.append(ele)
					ans[i] = ele
			elif len1 == 0:
				curr += 1
				len0 += 1
				zstk.append(curr)
				ans[i] = curr
			else:
				ele = ostk.popleft()
				len1 -= 1
				len0 += 1
				zstk.append(ele)
				ans[i] = ele
		yield curr
		yield ' '.join((str(x) for x in ans))
t = int(input())
ans = gift()
print(*ans, sep='\n')


import sys
import os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
depth = 1000005
mod = 1000000007
sys.setrecursionlimit(depth)
from math import inf, gcd, log
from collections import defaultdict
for _ in range(int(input())):
	(n, s) = (int(input()), str(input()))
	(zer, one, last) = ([], [], 0)
	ans = [0 for _ in range(n)]
	for i in range(n):
		if s[i] == '1':
			if len(zer):
				val = zer.pop()
				one.append(val)
				ans[i] = val
			else:
				last = last + 1
				one.append(last)
				ans[i] = last
		elif len(one):
			val = one.pop()
			zer.append(val)
			ans[i] = val
		else:
			last = last + 1
			zer.append(last)
			ans[i] = last
	print(last)
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	l = input()
	one = []
	zero = []
	d = {j: 0 for j in range(n)}
	r = 0
	for j in range(n):
		if l[j] == '0':
			if len(one) == 0:
				r = r + 1
				zero.append(r)
				d[j] = r
			else:
				zero.append(one.pop())
			d[j] = zero[-1]
		if l[j] == '1':
			if len(zero) == 0:
				r = r + 1
				one.append(r)
				d[j] = r
			else:
				one.append(zero.pop())
				d[j] = one[-1]
	print(r)
	for j in range(n):
		print(d[j], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	m = []
	d = [[], []]
	c = 0
	for i in s:
		i = int(i)
		if i == 0:
			if d[1]:
				x = d[1].pop()
				d[0].append(x)
				m.append(x)
			else:
				c += 1
				d[0].append(c)
				m.append(c)
		elif d[0]:
			x = d[0].pop()
			d[1].append(x)
			m.append(x)
		else:
			c += 1
			d[1].append(c)
			m.append(c)
	print(len(set(m)))
	print(*m)


def op(val):
	return '1' if val == '0' else '0'
t = int(input())
while t > 0:
	n = int(input())
	bin_str = list(input())
	req = {}
	ans = 0
	loc = [0 for i in range(n)]
	for i in range(n):
		s = bin_str[i]
		found = False
		if s in req and len(req[s]) > 0:
			loc[i] = str(req[s].pop())
			o = op(s)
			if o in req:
				req[o].append(loc[i])
			else:
				req[o] = [loc[i]]
		else:
			ans += 1
			o = op(s)
			loc[i] = str(ans)
			if o in req:
				req[o].append(ans)
			else:
				req[o] = [ans]
	print(ans)
	print(' '.join(loc))
	t -= 1


import sys
from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	s = input()
	res = [0] * n
	s0 = []
	s1 = []
	c = 1
	for i in range(n):
		if s[i] == '0':
			if len(s1) == 0:
				s0.append(c)
				res[i] = c
				c += 1
			else:
				s0.append(s1[-1])
				res[i] = s1[-1]
				s1.pop()
		elif len(s0) == 0:
			s1.append(c)
			res[i] = c
			c += 1
		else:
			s1.append(s0[-1])
			res[i] = s0[-1]
			s0.pop()
	print(c - 1)
	print(*res)


t = int(input())
for _ in range(0, t):
	n = int(input())
	st = str(input())
	if st[0] == '0':
		k = 1
		p = 1
		c = 0
	else:
		k = 1
		p = -1
		c = 1
	ans = 0
	q = [1]
	kmax = 0
	for i in range(1, len(st)):
		if st[i] == '0':
			k += 1
			if st[i - 1] == '1':
				q.append(abs(p))
			else:
				p += 1
				if p == 0:
					if c == 1:
						p = q[-1] + 1
					else:
						p = max(q) + 1
				c = 0
				q.append(abs(p))
			kmax = max(kmax, k)
		else:
			k -= 1
			if st[i - 1] == '0':
				q.append(abs(p))
			else:
				p -= 1
				if p == 0:
					if c == 0:
						p = -(q[-1] + 1)
					else:
						p = -(max(q) + 1)
				c = 1
				q.append(abs(p))
			kmax = max(abs(kmax), abs(k))
	print(max(q))
	print(*q)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var, end='\n'):
	sys.stdout.write(str(var) + end)

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	s = data()
	answer = [0] * n
	cnt = 1
	(z, o) = (deque(), deque())
	for i in range(n):
		if s[i] == '0':
			if not o and (not z):
				answer[i] = cnt
				z.append(cnt)
			elif not o:
				answer[i] = cnt + 1
				cnt += 1
				z.append(cnt)
			else:
				temp = o.popleft()
				answer[i] = temp
				z.append(temp)
		elif not o and (not z):
			answer[i] = cnt
			o.append(cnt)
		elif not z:
			answer[i] = cnt + 1
			cnt += 1
			o.append(cnt)
		else:
			temp = z.popleft()
			answer[i] = temp
			o.append(temp)
	out(max(answer))
	outa(*answer)


from heapq import *
for i in range(int(input())):
	n = int(input())
	b1 = list(input())
	b = [int(i) for i in b1]
	ask0 = []
	ask1 = []
	ss = [0 for i in range(n)]
	mxx = 1
	for i in range(n):
		e = b[i]
		if e == 0:
			if len(ask0) > 0:
				giveTo = heappop(ask0)
			else:
				giveTo = mxx
				mxx += 1
			ss[i] = giveTo
			heappush(ask1, giveTo)
		else:
			if len(ask1) > 0:
				giveTo = heappop(ask1)
			else:
				giveTo = mxx
				mxx += 1
			ss[i] = giveTo
			heappush(ask0, giveTo)
	mx = max(ss)
	print(mx)
	print(' '.join([str(i) for i in ss]))


testCases = int(input())
for _ in range(testCases):
	n = int(input())
	ar = list(input())
	flags = [[], []]
	count = 0
	for (idx, b) in enumerate(ar):
		b = int(b)
		if not b and flags[1]:
			ar[idx] = flags[1][0]
			temp = flags[1].pop(0)
			flags[0].append(temp)
		elif b and flags[0]:
			ar[idx] = flags[0][0]
			temp = flags[0].pop(0)
			flags[1].append(temp)
		else:
			count += 1
			ar[idx] = count
			flags[b].append(count)
	print(count)
	print(*ar)


T = int(input())
for t in range(T):
	N = input()
	s = input()
	zero_ends = []
	one_ends = []
	res = []
	a = 0
	for x in s:
		if x == '0':
			if one_ends:
				ai = one_ends.pop()
				zero_ends.append(ai)
				res.append(ai)
			else:
				a += 1
				res.append(a)
				zero_ends.append(a)
		elif zero_ends:
			ai = zero_ends.pop()
			one_ends.append(ai)
			res.append(ai)
		else:
			a += 1
			res.append(a)
			one_ends.append(a)
	print(a)
	print(' '.join((str(a) for a in res)))


t = int(input())
for i in range(t):
	n = int(input())
	s = input().strip()
	an = [1]
	z = []
	o = []
	c = 1
	if s[0] == '1':
		z.append(1)
	else:
		o.append(1)
	for j in range(1, n):
		if s[j] == '0':
			if z != []:
				p = z[-1]
				o.append(p)
				an.append(p)
				del z[-1]
			else:
				c = c + 1
				o.append(c)
				an.append(c)
		elif o != []:
			p = o[-1]
			z.append(p)
			an.append(p)
			del o[-1]
		else:
			c = c + 1
			an.append(c)
			z.append(c)
	print(c)
	print(' '.join(map(str, an)))


t = int(input())
for _ in range(t):
	n = int(input())
	li = input()
	zl = []
	ol = []
	ans = [0] * len(li)
	c = 0
	muls = 1
	for i in li:
		if i == '0':
			if len(ol) > 0:
				ans[c] = ol.pop()
				zl.append(ans[c])
			else:
				ans[c] = muls
				zl.append(muls)
				muls = muls + 1
		elif len(zl) > 0:
			ans[c] = zl.pop()
			ol.append(ans[c])
		else:
			ans[c] = muls
			ol.append(muls)
			muls = muls + 1
		c += 1
	print(max(ans))
	for i in ans:
		print(i, end=' ')
	print()


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	ans = [1]
	curr = 1
	ones = set([1] if s[0] == '1' else [])
	zeros = set([1] if s[0] == '0' else [])
	for i in range(1, n):
		if s[i] == '1':
			if zeros:
				for j in zeros:
					break
				zeros.remove(j)
				ones.add(j)
				ans.append(j)
			else:
				curr += 1
				ones.add(curr)
				ans.append(curr)
		elif ones:
			for j in ones:
				break
			ones.remove(j)
			zeros.add(j)
			ans.append(j)
		else:
			curr += 1
			zeros.add(curr)
			ans.append(curr)
	print(str(max(ans)) + '\n')
	ans = ' '.join(list(map(str, ans)))
	print(ans + '\n')


cases = int(input())
for t in range(cases):
	n = int(input())
	s = input()
	d = {'0': [], '1': []}
	v = []
	c = 1
	for i in s:
		if i == '0':
			if d['1']:
				val = d['1'].pop()
				d['0'].append(val)
			else:
				d['0'].append(c)
				c += 1
		elif d['0']:
			val = d['0'].pop()
			d['1'].append(val)
		else:
			d['1'].append(c)
			c += 1
		v.append(d[i][-1])
	print(max(v))
	print(*v)


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	zero = []
	one = []
	ans = []
	count = 0
	for i in range(0, len(a)):
		if a[i] == '0':
			if len(zero) > 0:
				p = zero.pop()
				one.append(p)
				ans.append(p)
			else:
				count += 1
				one.append(count)
				ans.append(count)
		elif len(one) > 0:
			p = one.pop()
			zero.append(p)
			ans.append(p)
		else:
			count += 1
			zero.append(count)
			ans.append(count)
	print(len(set(ans)))
	print(*ans)


t = int(input())
while t:
	t -= 1
	x = int(input())
	y = input()
	a = []
	b = []
	gg = []
	k = 1
	for i in y:
		if i == '0':
			if len(b) == 0:
				a.append(k)
				gg.append(k)
				k += 1
			else:
				x = b.pop()
				gg.append(x)
				a.append(x)
		if i == '1':
			if len(a) == 0:
				b.append(k)
				gg.append(k)
				k += 1
			else:
				x = a.pop()
				gg.append(x)
				b.append(x)
	print(len(a) + len(b))
	for i in gg:
		print(i, end=' ')
	print()


from collections import deque
for t in range(int(input())):
	n = int(input())
	s = input()
	ans = []
	(pos0, pos1) = (deque(), deque())
	for i in range(n):
		val = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(val)
			else:
				val = pos1.pop()
				pos0.append(val)
		elif len(pos0) == 0:
			pos1.append(val)
		else:
			val = pos0.pop()
			pos1.append(val)
		ans.append(val)
	print(len(pos0) + len(pos1))
	for i in ans:
		print(i + 1, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = input()
	sind = [0] * n
	c0 = set()
	c1 = set()
	cs = 0
	for i in range(n):
		if s[i] == '1':
			if len(c0) == 0:
				cs += 1
				sind[i] = cs
				c1.add(cs)
			else:
				x = c0.pop()
				sind[i] = x
				c1.add(x)
		elif len(c1) == 0:
			cs += 1
			sind[i] = cs
			c0.add(cs)
		else:
			x = c1.pop()
			sind[i] = x
			c0.add(x)
	print(cs)
	print(*sind)


import sys
input = sys.stdin.readline

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0, hi=None):
	if hi == None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	ans = [None] * n
	start = 1
	one = set()
	zero = set()
	for i in range(n):
		if s[i] == '1':
			if not zero:
				one.add(start)
				ans[i] = start
				start += 1
			else:
				y = None
				for x in zero:
					y = x
					break
				zero.remove(y)
				ans[i] = y
				one.add(y)
		elif not one:
			zero.add(start)
			ans[i] = start
			start += 1
		else:
			y = None
			for x in one:
				y = x
				break
			one.remove(y)
			ans[i] = y
			zero.add(y)
	print(start - 1)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	l = input()
	m = []
	d = {0: [], 1: []}
	c = 0
	for i in l:
		a = int(i)
		b = int(not a)
		if len(d[b]) != 0:
			p = d[b].pop()
			m.append(p)
			d[a].append(p)
		else:
			c += 1
			m.append(c)
			d[a].append(c)
	print(c)
	print(*m, sep=' ')


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
from heapq import heappush, heappop
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
t = ip()
for _ in range(t):
	n = ip()
	s = ips()
	arr = [None] * n
	stack1 = []
	stack0 = []
	ans = [None] * n
	pos = 0
	for i in range(n):
		if s[i] == '0':
			if len(stack1) == 0:
				pos += 1
				stack0.append(pos)
				ans[i] = pos
			else:
				ch = stack1.pop()
				ans[i] = ch
				stack0.append(ch)
		elif len(stack0) == 0:
			pos += 1
			stack1.append(pos)
			ans[i] = pos
		else:
			ch = stack0.pop()
			ans[i] = ch
			stack1.append(ch)
	print(len(set(ans)))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	zero = []
	one = []
	count = 0
	b = [0] * n
	for i in range(0, n):
		if s[i] == '0':
			if len(one) == 0:
				count += 1
				zero.append(count)
				b[i] = zero[-1]
			else:
				x = one[-1]
				one.pop()
				zero.append(x)
				b[i] = zero[-1]
		elif len(zero) == 0:
			count += 1
			one.append(count)
			b[i] = one[-1]
		else:
			x = zero[-1]
			zero.pop()
			one.append(x)
			b[i] = one[-1]
	print(count)
	print(*b)


def solve():
	for _ in range(ii()):
		n = ii()
		s = si()
		p0 = []
		p1 = []
		c = [-1] * n
		for i in range(n):
			len0 = len(p0)
			len1 = len(p1)
			newpos = len0 + len1
			if s[i] == '0':
				if len1 == 0:
					p0.append(newpos)
				else:
					newpos = p1.pop()
					p0.append(newpos)
			elif len0 == 0:
				p1.append(newpos)
			else:
				newpos = p0.pop()
				p1.append(newpos)
			c[i] = newpos + 1
		print(len(p0) + len(p1))
		print(*c)
ii = lambda : int(input())
mi = lambda : map(int, input().split())
li = lambda : list(mi())
si = lambda : input()
solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = [0] * n
	c = 0
	q = [[], []]
	for i in range(n):
		x = int(s[i]) ^ 1
		if len(q[x]) == 0:
			c = c + 1
			ans[i] = c
		else:
			ans[i] = q[x][-1]
			q[x].pop()
		q[x ^ 1].append(ans[i])
	print(max(ans))
	print(*ans)


for ip in [*open(0)][2::2]:
	a = list(map(int, ip.strip()))
	n = len(a)
	(p0, p1, ans) = ([], [], [])
	for x in a:
		np = len(p0) + len(p1)
		if x == 0:
			if p1:
				np = p1.pop()
				p0.append(np)
			else:
				p0.append(np)
		elif p0:
			np = p0.pop()
			p1.append(np)
		else:
			p1.append(np)
		ans.append(np + 1)
	print(len(p0) + len(p1))
	print(*ans)


for testcases in range(int(input())):
	num = int(input())
	s = input()
	ans = []
	flags = {0: [], 1: []}
	box = 0
	key = [0, 0]
	for i in range(num):
		if key[(int(s[i]) + 1) % 2] == 0:
			box += 1
			key[int(s[i])] += 1
			flags[int(s[i])].append(box)
			ans.append(box)
		else:
			key[int(s[i])] += 1
			key[(int(s[i]) + 1) % 2] -= 1
			flags[int(s[i])].append(flags[(int(s[i]) + 1) % 2][-1])
			ans.append(flags[(int(s[i]) + 1) % 2].pop(-1))
	print(box)
	print(*ans)


def modinv(n, p):
	return pow(n, p - 2, p)

def main():
	for case in range(int(input())):
		n = int(input())
		s = input()
		ans = [0] * n
		zero_last = set()
		one_last = set()
		k = 0
		for i in range(n):
			c = int(s[i])
			if c == 0:
				if len(one_last) == 0:
					k += 1
					zero_last.add(k)
					ans[i] = k
				else:
					t = one_last.pop()
					zero_last.add(t)
					ans[i] = t
			elif len(zero_last) == 0:
				k += 1
				one_last.add(k)
				ans[i] = k
			else:
				t = zero_last.pop()
				one_last.add(t)
				ans[i] = t
		print(max(ans))
		print(*ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	one = []
	zero = []
	ans = []
	cl = 0
	for (i, c) in enumerate(s):
		if c == '1':
			if zero:
				x = zero.pop()
				ans.append(x)
				one.append(x)
			else:
				cl += 1
				ans.append(cl)
				one.append(cl)
		elif one:
			x = one.pop()
			ans.append(x)
			zero.append(x)
		else:
			cl += 1
			ans.append(cl)
			zero.append(cl)
	print(cl)
	print(*ans)


T = int(input())
for _ in range(T):
	n = int(input())
	string = input()
	ans = []
	zeroq = []
	oneq = []
	for i in range(n):
		counter = len(zeroq) + len(oneq)
		if string[i] == '0':
			if not oneq:
				zeroq.append(counter)
			else:
				counter = oneq[-1]
				zeroq.append(counter)
				del oneq[-1]
		elif not zeroq:
			oneq.append(counter)
		else:
			counter = zeroq[-1]
			oneq.append(counter)
			del zeroq[-1]
		ans.append(str(counter + 1))
	print(len(zeroq) + len(oneq))
	print(' '.join(ans))


for _ in range(int(input())):
	n = int(input())
	(ls0, ls1) = ([], [])
	ctr = 1
	s = input()
	an = 0
	ans = ''
	for i in range(n):
		if s[i] == '1':
			if len(ls0):
				ls1.append(ls0[-1])
				ls0.pop()
				ans += str(ls1[-1]) + ' '
			else:
				ls1.append(ctr)
				ans += str(ctr) + ' '
				an = max(an, ctr)
				ctr += 1
		elif len(ls1):
			ls0.append(ls1[-1])
			ls1.pop()
			ans += str(ls0[-1]) + ' '
		else:
			ls0.append(ctr)
			ans += str(ctr) + ' '
			an = max(an, ctr)
			ctr += 1
	print(an)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	s = [True if x == '1' else False for x in input()]
	sub = [[], []]
	ans = [None for i in range(n)]
	m = 1
	for i in range(n):
		e = not s[i]
		if len(sub[e]) != 0:
			f = sub[e].pop()
			ans[i] = f
			sub[s[i]].append(f)
		else:
			ans[i] = m
			sub[s[i]].append(m)
			m += 1
	print(m - 1)
	for i in range(len(ans) - 1):
		print(ans[i], end=' ')
	print(ans[-1])


from collections import deque
t = int(input())
while t > 0:
	nextSubSeqIdToUse = 1
	subSeqsWhichRequireZeroNext = deque()
	subSeqsWhichRequireOneNext = deque()
	n = int(input())
	string = input()
	charWiseSubSeqId = []
	for char in string:
		if char == '0':
			if len(subSeqsWhichRequireZeroNext) > 0:
				subSeqForChar = subSeqsWhichRequireZeroNext.popleft()
				charWiseSubSeqId.append(subSeqForChar)
				subSeqsWhichRequireOneNext.append(subSeqForChar)
			else:
				subSeqForChar = nextSubSeqIdToUse
				nextSubSeqIdToUse += 1
				charWiseSubSeqId.append(subSeqForChar)
				subSeqsWhichRequireOneNext.append(subSeqForChar)
		elif char == '1':
			if len(subSeqsWhichRequireOneNext) > 0:
				subSeqForChar = subSeqsWhichRequireOneNext.popleft()
				charWiseSubSeqId.append(subSeqForChar)
				subSeqsWhichRequireZeroNext.append(subSeqForChar)
			else:
				subSeqForChar = nextSubSeqIdToUse
				nextSubSeqIdToUse += 1
				charWiseSubSeqId.append(subSeqForChar)
				subSeqsWhichRequireZeroNext.append(subSeqForChar)
	print(nextSubSeqIdToUse - 1)
	print(' '.join(map(str, charWiseSubSeqId)))
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	arr = []
	for i in range(n):
		arr.append(int(s[i]))
	ones = []
	zeros = []
	vals = []
	k = 0
	for i in range(n):
		p = arr[i]
		if p == 0:
			if ones == []:
				zeros.append(k + 1)
				vals.append(k + 1)
				k += 1
			else:
				zeros.append(ones[-1])
				vals.append(ones[-1])
				ones.pop()
		elif zeros == []:
			ones.append(k + 1)
			vals.append(k + 1)
			k += 1
		else:
			ones.append(zeros[-1])
			vals.append(ones[-1])
			zeros.pop()
	print(max(vals))
	for i in vals:
		print(i, end=' ')
	print()


t = int(input())
for tt in range(t):
	n = int(input())
	s = input()
	(ones, zeros) = ([], [])
	res = []
	nums = 0
	for i in range(n):
		which = 0
		if s[i] == '0':
			if len(ones) == 0:
				nums += 1
				which = nums
				zeros += [nums]
			else:
				which = ones.pop()
				zeros += [which]
		elif len(zeros) == 0:
			nums += 1
			which = nums
			ones += [nums]
		else:
			which = zeros.pop()
			ones += [which]
		res += [which]
	print(nums)
	print(' '.join([str(x) for x in res]))


for t in range(int(input())):
	n = int(input())
	s = input()
	k = {'0': [], '1': []}
	out = 0
	ans = ''
	for i in s:
		if i == '0':
			if not k['1']:
				out += 1
				k[i].append(out)
				ans += ' ' + str(out)
			else:
				val = k['1'].pop()
				ans += ' ' + str(val)
				k[i].append(val)
		elif not k['0']:
			out += 1
			k[i].append(out)
			ans += ' ' + str(out)
		else:
			val = k['0'].pop()
			ans += ' ' + str(val)
			k[i].append(val)
	print(out)
	print(ans[1:])


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = list(map(int, list(input())))
	base = s[0]
	wall = 1
	l = [0] * n
	k = 1
	for i in range(n):
		if i == 0:
			l[0] = 1
			continue
		if s[i] == base:
			wall += 1
			l[i] = wall
			k = max(wall, k)
		else:
			if wall == 0:
				k += 1
				l[i] = k
				continue
			wall -= 1
			l[i] = wall + 1
			k = max(wall + 1, k)
	print(k)
	for i in range(n):
		print(l[i], end=' ')
	print()


t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	min1 = 1
	max1 = 1
	ans = [1]
	curr = 1
	if n == 1:
		print('1\n1')
		continue
	for i in range(1, n):
		if s[i] == s[i - 1]:
			if s[i] == '1':
				curr += 1
				ans.append(curr)
			else:
				curr -= 1
				ans.append(curr)
		else:
			ans.append(curr)
		if min1 > curr:
			min1 = curr
		if max1 < curr:
			max1 = curr
	print(max1 - min1 + 1)
	for i in ans:
		print(i - min1 + 1, end=' ')


T = int(input())
for _ in range(T):
	n = int(input())
	a = input()
	count = 1
	zer = []
	one = []
	res = [0 for i in range(n)]
	for i in range(n):
		if a[i] == '0':
			if one == []:
				zer.append(count)
				count += 1
				res[i] = zer[-1]
			else:
				x = one.pop()
				zer.append(x)
				res[i] = zer[-1]
		if a[i] == '1':
			if zer == []:
				one.append(count)
				count += 1
				res[i] = one[-1]
			else:
				x = zer.pop()
				one.append(x)
				res[i] = one[-1]
	print(count - 1)
	print(*res)


import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
	n = int(input())
	a = input()[:-1]
	ans = [-1] * n
	now = 1
	zero = deque([])
	one = deque([])
	for i in range(n):
		if a[i] == '0':
			if len(one) == 0:
				ans[i] = now
				zero.append(now)
				now += 1
			else:
				ans[i] = one.popleft()
				zero.append(ans[i])
		elif len(zero) == 0:
			ans[i] = now
			one.append(now)
			now += 1
		else:
			ans[i] = zero.popleft()
			one.append(ans[i])
	print(max(ans))
	print(*ans)


def solve(A):
	seqs = list()
	set0 = set()
	set1 = set()
	indxs = [-1 for i in range(len(A))]
	for (i, a) in enumerate(A):
		if a == 0:
			if len(set1) > 0:
				for s1 in set1:
					idx1 = s1
					break
				seqs[idx1].append(0)
				set1.remove(idx1)
				set0.add(idx1)
				indxs[i] = idx1
			else:
				seqs.append([0])
				set0.add(len(seqs) - 1)
				indxs[i] = len(seqs) - 1
		elif len(set0) > 0:
			for s0 in set0:
				idx0 = s0
				break
			seqs[idx0].append(1)
			set0.remove(idx0)
			set1.add(idx0)
			indxs[i] = idx0
		else:
			seqs.append([1])
			set1.add(len(seqs) - 1)
			indxs[i] = len(seqs) - 1
	print(len(seqs))
	for indx in indxs:
		print(indx + 1, end=' ')
	print()
t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input()))
	solve(A)


for _ in range(int(input())):
	n = int(input())
	d = {0: [], 1: []}
	s = list(map(int, list(input())))
	index = []
	count = 0
	for i in range(n):
		c = s[i]
		x = int(not c)
		if len(d[x]) > 0:
			ind = d[x].pop()
			d[c].append(ind)
		else:
			count += 1
			d[c].append(count)
			ind = count
		index.append(ind)
	print(count)
	print(*index)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
from decimal import Decimal
from fractions import Fraction
INF = float('inf')
mod = int(1000000000.0) + 7
for t in range(int(data())):
	n = int(data())
	s = data()
	(cnt, u0, u1) = (0, 0, 0)
	(l0, l1) = ([], [])
	ans = [0] * n
	for i in range(n):
		if s[i] == '0':
			if u1 == 0:
				cnt += 1
				ans[i] = cnt
			else:
				ans[i] = l1.pop()
				u1 -= 1
			l0.append(ans[i])
			u0 += 1
		else:
			if u0 == 0:
				cnt += 1
				ans[i] = cnt
			else:
				ans[i] = l0.pop()
				u0 -= 1
			l1.append(ans[i])
			u1 += 1
	out(cnt)
	outl(ans)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = input()
	(a, b, ans) = ([], [], [])
	for i in s[:-1]:
		if i == '0':
			if b:
				a.append(b.pop())
			else:
				a.append(len(a) + len(b) + 1)
			ans.append(a[-1])
		else:
			if a:
				b.append(a.pop())
			else:
				b.append(len(a) + len(b) + 1)
			ans.append(b[-1])
	print(max(ans))
	print(*ans)


t = int(input())
for q in range(t):
	n = int(input())
	s = input()
	numOfSeq = 0
	ones = []
	zeros = []
	whichSeq = []
	for j in range(n):
		if s[j] == '0':
			if len(ones) == 0:
				numOfSeq += 1
				whichSeq.append(numOfSeq)
				zeros.append(numOfSeq)
			else:
				curSeq = ones.pop()
				whichSeq.append(curSeq)
				zeros.append(curSeq)
		elif len(zeros) == 0:
			numOfSeq += 1
			whichSeq.append(numOfSeq)
			ones.append(numOfSeq)
		else:
			curSeq = zeros.pop()
			whichSeq.append(curSeq)
			ones.append(curSeq)
	print(numOfSeq)
	for i in range(n):
		print(whichSeq[i], end=' ')
	print()


T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	one_list = []
	zero_list = []
	ans_counter = 0
	ans = []
	for i in range(n):
		if s[i] == '1':
			if zero_list:
				p = zero_list.pop()
				one_list.append(p)
				ans.append(p)
			else:
				ans_counter += 1
				ans.append(ans_counter)
				one_list.append(ans_counter)
		elif one_list:
			p = one_list.pop()
			zero_list.append(p)
			ans.append(p)
		else:
			ans_counter += 1
			ans.append(ans_counter)
			zero_list.append(ans_counter)
	print(ans_counter)
	print(*ans)


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heapreplace, heappushpop
from bisect import bisect_right, bisect_left

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
mod = 1000000007
res = ['NO', 'YES']
(test, test_case) = (0, 1)
test_case = ii()
while test < test_case:
	test += 1
	n = ii()
	a = list(map(int, si()))
	ans = []
	mx = 1
	z = {1}
	o = {1}
	for i in range(n):
		if a[i]:
			if not o:
				o.add(mx + 1)
				mx += 1
			x = o.pop()
			z.add(x)
		else:
			if not z:
				z.add(mx + 1)
				mx += 1
			x = z.pop()
			o.add(x)
		ans.append(x)
	print(max(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = input()
	(res, k, d, t) = ([-1] * n, 0, {0: [], 1: []}, 2)
	for i in range(n):
		cur = int(a[i])
		alt = 1 - cur
		if len(d[alt]) > 0:
			t = d[alt].pop()
			d[cur].append(t)
		else:
			k += 1
			d[cur].append(k)
			t = k
		res[i] = t
	print(k)
	print(*res)


import bisect
import copy
import fractions
import heapq
import math
import random
import sys
T = int(input())
for t in range(T):
	N = int(input())
	S = input()
	one_ready = []
	zero_ready = []
	assignments = []
	subs = 0
	for ch in S:
		if ch == '0':
			if len(zero_ready) == 0:
				subs += 1
				heapq.heappush(one_ready, subs)
				assignments.append(subs)
			else:
				assign = heapq.heappop(zero_ready)
				heapq.heappush(one_ready, assign)
				assignments.append(assign)
		if ch == '1':
			if len(one_ready) == 0:
				subs += 1
				heapq.heappush(zero_ready, subs)
				assignments.append(subs)
			else:
				assign = heapq.heappop(one_ready)
				heapq.heappush(zero_ready, assign)
				assignments.append(assign)
	print(subs)
	print(' '.join(list(map(str, assignments))))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(input())
	one = []
	zero = []
	ans = []
	new = 1
	for i in range(n):
		if a[i] == '1':
			if len(zero) >= 1:
				c = zero[-1]
				zero.pop()
				one.append(c)
				ans.append(c)
			else:
				c = new
				one.append(c)
				ans.append(c)
				new += 1
		elif len(one) >= 1:
			c = one[-1]
			one.pop()
			zero.append(c)
			ans.append(c)
		else:
			c = new
			zero.append(c)
			ans.append(c)
			new += 1
	print(max(ans))
	print(*ans)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def shift(a, i, num):
	for _ in range(num):
		(a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
	return abs(x - y) <= 1e-09

def getAngle(a, b, c):
	ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
	return ang + 360 if ang < 0 else ang

def getLength(a, b):
	return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def isSubsetSum(arr, n, summ):
	subarr = [[False for i in range(summ + 1)] for i in range(n + 1)]
	for i in range(n + 1):
		subarr[i][0] = True
	for i in range(1, summ + 1):
		subarr[0][i] = False
	for i in range(1, n + 1):
		for j in range(1, summ + 1):
			if j < arr[i - 1]:
				subarr[i][j] = subarr[i - 1][j]
			if j >= arr[i - 1]:
				subarr[i][j] = subarr[i - 1][j] or subarr[i - 1][j - arr[i - 1]]
	return subarr[n][summ]

def bfs(v, adj, onpath):
	s = set()
	d = defaultdict(set)
	q = deque([])
	s.add(0)
	d[0].add(0)
	q.append((0, 0))
	while len(q) > 0:
		(v, depth) = q.popleft()
		for u in adj[v]:
			if u not in s:
				s.add(u)
				d[depth + 1].add(u)
				q.append((u, depth + 1))
	return d

def solution(s, n):
	zero = set()
	one = set()
	cnt = 1
	set_nums = [0 for i in range(n)]
	for (i, x) in enumerate(s):
		if x == '0':
			if len(one) > 0:
				set_num = one.pop()
				set_nums[i] = set_num
				zero.add(set_num)
			else:
				zero.add(cnt)
				set_nums[i] = cnt
				cnt += 1
		if x == '1':
			if len(zero) > 0:
				set_num = zero.pop()
				set_nums[i] = set_num
				one.add(set_num)
			else:
				one.add(cnt)
				set_nums[i] = cnt
				cnt += 1
	return f'{cnt - 1}\n' + ' '.join(map(str, set_nums))

def main():
	T = 1
	T = ri()
	for i in range(T):
		n = ri()
		s = rs()
		x = solution(s, n)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

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

	def inputi():
		return stdin.buffer.readline()

def solve():
	n = int(input())
	ss = input()
	res = []
	zs = []
	os = []
	nxt = 1
	for s in ss:
		if s == '0':
			if os:
				v = os.pop()
			else:
				v = nxt
				nxt += 1
			zs.append(v)
			res.append(v)
		else:
			if zs:
				v = zs.pop()
			else:
				v = nxt
				nxt += 1
			os.append(v)
			res.append(v)
	print(nxt - 1)
	print(' '.join(map(str, res)))

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


from sys import stdin, stdout

def INPUT():
	return list((int(i) for i in stdin.readline().split()))

def inp():
	return stdin.readline()

def out(x):
	return stdout.write(x)
import math
for _ in range(int(input())):
	n = int(input())
	s = input()
	A = []
	for i in range(len(s)):
		A.append(int(s[i]))
	X = []
	present = A[i]
	zero = 0
	one = 0
	Z = []
	I = []
	for i in range(len(s)):
		if A[i] == 0:
			if one > 0:
				zero += 1
				one -= 1
				X.append(I[-1])
				Z.append(I.pop())
			else:
				Z.append(zero + 1)
				zero += 1
				X.append(Z[-1])
		elif zero > 0:
			one += 1
			zero -= 1
			X.append(Z[-1])
			I.append(Z.pop())
		else:
			I.append(one + 1)
			one += 1
			X.append(I[-1])
	print(max(X))
	print(*X)


production = True
import sys, math, collections, bisect, itertools, heapq, decimal, random, copy, re

def input(f=0, m=0):
	if m > 0:
		return [input(f) for i in range(m)]
	else:
		l = sys.stdin.readline()[:-1]
		if f >= 10:
			u = False
			f = int(str(f)[-1])
		else:
			u = True
		if f == 0:
			p = [l]
		elif f == 1:
			p = list(map(int, l.split()))
		elif f == 2:
			p = list(map(float, l.split()))
		elif f == 3:
			p = list(l)
		elif f == 4:
			p = list(map(int, list(l)))
		elif f == 5:
			p = l.split()
		return p if u else p[0]

def out(l, f=0, n=True):
	if f == 0:
		p = str(l)
	elif f == 1:
		p = ' '.join(map(str, l))
	elif f == 2:
		p = '\n'.join(map(str, l))
	elif f == 3:
		p = ''.join(map(str, l))
	print(p, end='\n' if n else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c
ceil = lambda a, b: -(-a // b)
flip = lambda a: a + 1 & 1

def mapl(i, f=0):
	if f == 0:
		return list(map(int, i))
	elif f == 1:
		return list(map(str, i))
	elif f == 2:
		return list(map(list, i))

def solve():
	n = input(11)
	s = input(4)
	o = []
	p = [[], []]
	t = 0
	for i in s:
		if not p[i]:
			t += 1
			p[flip(i)].append(t)
			r = t
		else:
			r = p[i].pop()
			p[flip(i)].append(r)
		o.append(r)
	out(t)
	out(o, 1)
	return
for i in range(input(11)):
	solve()


for _ in range(int(input())):
	n = int(input())
	s = input()
	seq = []
	one_ended = []
	zero_ended = []
	answer = ''
	for bit in s:
		if bit == '0':
			if len(one_ended) == 0:
				seq.append('0')
				zero_ended.append(len(seq) - 1)
				answer += str(len(seq)) + ' '
			else:
				seq[one_ended[-1]] += '0'
				answer += str(one_ended[-1] + 1) + ' '
				zero_ended.append(one_ended.pop())
		elif len(zero_ended) == 0:
			seq.append('1')
			one_ended.append(len(seq) - 1)
			answer += str(len(seq)) + ' '
		else:
			seq[zero_ended[-1]] += '1'
			answer += str(zero_ended[-1] + 1) + ' '
			one_ended.append(zero_ended.pop())
	print(len(seq))
	print(answer)


for _ in range(int(input())):
	n = int(input())
	str = input()
	pos = [[] for _ in range(2)]
	idx = [0] * n
	ans = 0
	for i in range(n):
		x = int(str[i]) ^ 1
		if len(pos[x]) == 0:
			ans += 1
			idx[i] = ans
		else:
			idx[i] = pos[x][-1]
			pos[x].pop()
		pos[x ^ 1].append(idx[i])
	print(ans)
	print(*idx)


import sys
from collections import defaultdict
t = 1
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, list(input())))
	x = []
	curr = 0
	op = []
	nozil = 0
	nooil = 0
	for j in range(n):
		if a[j] == 1 and nooil or (a[j] == 0 and nozil):
			xx = x.index(a[j])
			op.append(xx + 1)
			x[xx] = abs(a[j] - 1)
			if a[j] == 1:
				nozil += 1
				nooil -= 1
			else:
				nooil += 1
				nozil -= 1
		else:
			x.append(abs(a[j] - 1))
			curr += 1
			op.append(curr)
			if a[j] == 1:
				nozil += 1
			else:
				nooil += 1
	print(len(x))
	print(*op)


def read():
	return [int(x) for x in input().split()]
(cas,) = read()
for _ in range(cas):
	(n,) = read()
	s = input()
	zs = []
	os = []
	rs = []
	r = 0
	for i in range(n):
		if s[i] == '0':
			if len(os) == 0:
				r += 1
				rs.append(r)
				zs.append(r)
			else:
				p = os.pop()
				zs.append(p)
				rs.append(p)
		elif len(zs) == 0:
			r += 1
			rs.append(r)
			os.append(r)
		else:
			p = zs.pop()
			os.append(p)
			rs.append(p)
	print(r)
	print(' '.join((str(x) for x in rs)))


def main():
	res = ''
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, list(input())))
		b = []
		seq = [[], []]
		seq_total = 0
		for x in a:
			if seq[1 - x]:
				nseq = seq[1 - x][0]
				seq[x].append(nseq)
				del seq[1 - x][0]
			else:
				nseq = seq_total
				seq_total += 1
				seq[x].append(nseq)
			b.append(nseq + 1)
		print(seq_total)
		print(*b)
main()


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	n = int(input())
	string = [int(x) for x in input()]
	needsOne = set()
	needsZero = set()
	buckets = {}
	c = 0
	for (ind, val) in enumerate(string):
		if val == 1:
			if len(needsOne):
				cand = needsOne.pop()
				buckets[cand].append(ind)
				needsZero.add(cand)
			else:
				c += 1
				buckets[c] = [ind]
				needsZero.add(c)
		elif len(needsZero):
			cand = needsZero.pop()
			buckets[cand].append(ind)
			needsOne.add(cand)
		else:
			c += 1
			buckets[c] = [ind]
			needsOne.add(c)
	ans = ['0' for x in range(n)]
	for k in buckets:
		for val in buckets[k]:
			ans[val] = str(k)
	print(len(buckets))
	print(' '.join(ans))


t = int(input())
for i in range(t):
	n = int(input())
	s = str(input())
	s0 = []
	s1 = []
	l0 = 0
	l1 = 0
	if s[0] == '1':
		s0.append(1)
		l0 += 1
	else:
		s1.append(1)
		l1 += 1
	ans = [0] * n
	ans[0] = 1
	m = 1
	for j in range(1, n):
		if s[j] == '1':
			if l1 != 0:
				x = s1.pop()
				l1 -= 1
				ans[j] = x
				s0.append(x)
				m = max(m, x)
				l0 += 1
			else:
				s0.append(m + 1)
				l0 += 1
				m += 1
				ans[j] = m
		elif l0 != 0:
			x = s0.pop()
			l0 -= 1
			ans[j] = x
			s1.append(x)
			l1 += 1
			m = max(m, x)
		else:
			s1.append(m + 1)
			m += 1
			l1 += 1
			ans[j] = m
	print(max(ans))
	print(' '.join((str(x) for x in ans)))


import sys
input = sys.stdin.readline
from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	ls = []
	st0 = deque()
	st1 = deque()
	for i in range(n):
		if a[i] == '0':
			if st1:
				x = st1.popleft()
				st0.append(x)
			elif st0:
				x = st0[-1] + 1
				st0.append(x)
			else:
				x = 1
				st0.append(x)
		elif st0:
			x = st0.pop()
			st1.appendleft(x)
		elif st1:
			x = st1[-1] + 1
			st1.append(x)
		else:
			x = 1
			st1.append(x)
		ls.append(x)
	print(max(ls))
	print(*ls)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()[:-1]
	cnt = [[] for i in range(2)]
	ans = [0] * n
	for (i, char) in enumerate(s):
		if char == '1':
			if cnt[0]:
				ind = cnt[0].pop()
				cnt[1].append(ind)
			else:
				ind = len(cnt[1]) + 1
				cnt[1].append(ind)
		if char == '0':
			if cnt[1]:
				ind = cnt[1].pop()
				cnt[0].append(ind)
			else:
				ind = len(cnt[0]) + 1
				cnt[0].append(ind)
		ans[i] = ind
	print(max(ans))
	print(*ans)


from sys import stdin, stdout
from sys import maxsize
input = stdin.readline

def solve():
	pass
test = 1
test = int(input().strip())
for t in range(0, test):
	n = int(input().strip())
	s = list(input().strip())
	b = [-1] * n
	one = []
	zero = []
	cnt = 1
	for i in range(n):
		if s[i] == '0':
			if one == []:
				zero += [cnt]
				b[i] = cnt
				cnt += 1
			else:
				temp = one.pop()
				zero += [temp]
				b[i] = temp
		elif zero == []:
			one += [cnt]
			b[i] = cnt
			cnt += 1
		else:
			temp = zero.pop()
			one += [temp]
			b[i] = temp
	print(cnt - 1)

	def onedarr(a):
		for el in a:
			print(el, end=' ')
		print()
	onedarr(b)
	ans = solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	n0 = []
	n1 = []
	cnt = 0
	ans = []
	for i in range(n):
		if s[i] == '0':
			if len(n1) > 0:
				n0.append(n1.pop())
				ans.append(n0[-1])
			else:
				cnt += 1
				n0.append(cnt)
				ans.append(cnt)
		elif len(n0) > 0:
			n1.append(n0.pop())
			ans.append(n1[-1])
		else:
			cnt += 1
			n1.append(cnt)
			ans.append(cnt)
	print(cnt)
	print(' '.join(map(str, ans)))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	num = 0
	zeros = 0
	ones = 0
	d0 = set()
	d1 = set()
	a = []
	for x in s:
		if x == '1':
			if zeros > 0:
				temp = d0.pop()
				d1.add(temp)
				a.append(temp)
				zeros -= 1
			else:
				num += 1
				d1.add(num)
				a.append(num)
			ones += 1
		else:
			if ones > 0:
				temp = d1.pop()
				d0.add(temp)
				a.append(temp)
				ones -= 1
			else:
				num += 1
				d0.add(num)
				a.append(num)
			zeros += 1
	print(num)
	print(' '.join(map(str, a)))


import sys, os
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
input = lambda : sys.stdin.readline().strip()
li = lambda : list(map(int, input().split()))
I = lambda : int(input())
for _ in range(I()):
	n = I()
	s = list(map(int, list(input())))
	l = [0 for i in range(n)]
	zero = 0
	last_zero_set = []
	one = 0
	last_one_set = []
	for (index, i) in enumerate(s):
		if i == 1:
			if zero > 0:
				zero -= 1
				one += 1
				last_one_set.append(last_zero_set.pop())
			else:
				one += 1
				last_one_set.append(one)
			l[index] = last_one_set[-1]
		else:
			if one > 0:
				one -= 1
				zero += 1
				last_zero_set.append(last_one_set.pop())
			else:
				zero += 1
				last_zero_set.append(zero)
			l[index] = last_zero_set[-1]
	print(zero + one)
	print(*l)


for _ in range(int(input())):
	n = int(input())
	s = input()
	end0 = []
	end1 = []
	ans = [0] * n
	c = 1
	for i in range(n):
		if s[i] == '0':
			if len(end1) == 0:
				end0.append(c)
				ans[i] = c
				c += 1
			else:
				p = end1.pop()
				ans[i] = p
				end0.append(p)
		elif len(end0) == 0:
			end1.append(c)
			ans[i] = c
			c += 1
		else:
			p = end0.pop()
			ans[i] = p
			end1.append(p)
	print(c - 1)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = list(str(input()))
	a = [1]
	one = []
	zero = []
	if s[0] == '0':
		zero.append(1)
	else:
		one.append(1)
	ind = 1
	if n == 1:
		print(1)
		print(1)
	else:
		for i in range(1, n):
			if s[i] == '0':
				if len(one) == 0:
					ind += 1
					zero.append(ind)
					a.append(ind)
				else:
					a.append(one[0])
					zero.append(one[0])
					one.pop(0)
			elif len(zero) == 0:
				ind += 1
				one.append(ind)
				a.append(ind)
			else:
				a.append(zero[0])
				one.append(zero[0])
				zero.pop(0)
		print(max(a), *a)


import math
from decimal import *
for _ in range(int(input())):
	n = int(input())
	s = str(input())
	(pos1, pos0) = ([], [])
	mrk = [0] * n
	for m in range(n):
		tot = len(pos0) + len(pos1) + 1
		if s[m] == '0':
			if not pos1:
				pos0.append(tot)
			else:
				tot = pos1.pop()
				pos0.append(tot)
		elif not pos0:
			pos1.append(tot)
		else:
			tot = pos0.pop()
			pos1.append(tot)
		mrk[m] = str(tot)
	print(len(pos0) + len(pos1))
	print(' '.join(mrk))


import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
import collections as col

def solve():
	zeros = []
	ones = []
	N = getInt()
	S = listStr()
	count = 0
	ans = []
	for s in S:
		if s == '0':
			if not ones:
				count += 1
				zeros.append(count)
				ans.append(count)
			else:
				num = ones.pop()
				zeros.append(num)
				ans.append(num)
		elif not zeros:
			count += 1
			ones.append(count)
			ans.append(count)
		else:
			num = zeros.pop()
			ones.append(num)
			ans.append(num)
	print(count)
	print(*ans)
T = getInt()
for t in range(T):
	solve()


cases = int(input())
for i in range(cases):
	n = int(input())
	s = input()
	if '1' not in s or '0' not in s:
		print(n)
		ans = []
		for b in range(1, n + 1):
			ans.append(str(b))
		print(' '.join(ans))
		continue
	ans = []
	arr0 = []
	arr1 = []
	for k in range(n):
		ans.append(-1)
	for j in range(n):
		newpos = len(arr0) + len(arr1)
		char = s[j]
		if char == '0':
			if len(arr1) == 0:
				arr0.append(newpos)
			else:
				newpos = arr1[-1]
				del arr1[-1]
				arr0.append(newpos)
		elif len(arr0) == 0:
			arr1.append(newpos)
		else:
			newpos = arr0[-1]
			del arr0[-1]
			arr1.append(newpos)
		ans[j] = str(newpos + 1)
	print(len(arr0) + len(arr1))
	print(' '.join(ans))


list_input = lambda : list(map(int, input().split()))
int_input = lambda : int(input())

def count_vals(l):
	d = {}
	for i in l:
		d[i] = d.get(i, 0) + 1
	return d
for _ in range(int_input()):
	n = int_input()
	s = input()
	d = {0: [], 1: []}
	ans = []
	no = 1
	for i in range(n):
		if s[i] == '1':
			if len(d[0]) == 0:
				ans.append(no)
				d[1].append(no)
				no += 1
			else:
				x = d[0].pop()
				ans.append(x)
				d[1].append(x)
		elif len(d[1]) == 0:
			ans.append(no)
			d[0].append(no)
			no += 1
		else:
			x = d[1].pop()
			ans.append(x)
			d[0].append(x)
	print(no - 1)
	print(*ans)


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)
t = 1
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	s = stdin.readline().strip('\n')
	n = len(s)
	a = [-1] * n
	for i in range(n):
		a[i] = 1 if s[i] == '1' else -1
	ind = [1]
	sf = 1
	prv = s[0]
	for i in range(1, n):
		if prv == s[i] and s[i] == '1':
			sf += 1
			ind.append(sf)
		elif prv == s[i] and s[i] == '0':
			sf -= 1
			ind.append(sf)
		else:
			ind.append(sf)
		prv = s[i]
	d = {}
	cnt = 1
	an = []
	for i in range(len(ind)):
		if ind[i] not in d:
			d[ind[i]] = cnt
			cnt += 1
		an.append(d[ind[i]])
	print(max(an))
	print(*an)


import math
num_cases = int(input())
for _ in range(num_cases):
	n = int(input())
	arr = list(map(int, input().strip()))
	num = 0
	ending = [[], []]
	ans = []
	for elem in arr:
		if len(ending[1 - elem]) > 0:
			seq = ending[1 - elem].pop()
			ending[elem].append(seq)
			ans.append(seq)
		else:
			num += 1
			ending[elem].append(num)
			ans.append(num)
	print(num)
	for i in ans:
		print(i, end=' ')
	print()


import itertools
for i in range(0, int(input())):
	n = int(input())
	s = input()
	o = []
	f = []
	p = 0
	ans = []
	for i in range(0, n):
		if s[i] == '0':
			if len(f) == 0:
				ans.append(p + 1)
				o.append(p + 1)
				p += 1
			else:
				ans.append(f.pop())
				o.append(ans[-1])
		elif len(o) == 0:
			ans.append(p + 1)
			f.append(p + 1)
			p += 1
		else:
			ans.append(o.pop())
			f.append(ans[-1])
	print(max(ans))
	print(*ans)


def solve(n, s):
	pos0 = []
	pos1 = []
	answ = [0] * n
	for i in range(n):
		newpos = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(newpos)
			else:
				newpos = pos1.pop()
				pos0.append(newpos)
		elif len(pos0) == 0:
			pos1.append(newpos)
		else:
			newpos = pos0.pop()
			pos1.append(newpos)
		answ[i] = newpos
	print(len(pos0) + len(pos1))
	for i in answ:
		print(i + 1, '', end='')
	print()
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	solve(n, s)


t = int(input())
while t:
	n = int(input())
	s = str(input())
	ones = []
	zeroes = []
	count = 1
	ans = [0] * n
	for i in range(n):
		if s[i] == '1':
			if len(zeroes) == 0:
				ones.append(count)
				ans[i] = count
				count += 1
			else:
				ones.append(zeroes[-1])
				ans[i] = zeroes[-1]
				zeroes.pop()
		elif len(ones) == 0:
			zeroes.append(count)
			ans[i] = count
			count += 1
		else:
			zeroes.append(ones[-1])
			ans[i] = ones[-1]
			ones.pop()
	print(count - 1)
	print(*ans)
	t -= 1


import heapq
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	zeros = []
	ones = []
	nexts = 1
	ans = [0] * n
	for i in range(n):
		if s[i] == '0':
			if len(ones) != 0:
				tmp = heapq.heappop(ones)
				heapq.heappush(zeros, tmp)
			else:
				tmp = nexts
				nexts += 1
				heapq.heappush(zeros, tmp)
			ans[i] = tmp
		else:
			if len(zeros) != 0:
				tmp = heapq.heappop(zeros)
				heapq.heappush(ones, tmp)
			else:
				tmp = nexts
				nexts += 1
				heapq.heappush(ones, tmp)
			ans[i] = tmp
	print(max(ans))
	print(*ans)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	last0 = 0
	last1 = 0
	arr0 = [0 for i in range(n + 1)]
	arr1 = [0 for i in range(n + 1)]
	arr = [0 for i in range(n)]
	cur = 0
	res = 0
	for c in s:
		if c == '0':
			if last1 > 0:
				last0 += 1
				arr0[last0] = arr1[last1]
				last1 -= 1
			else:
				last0 += 1
				arr0[last0] = last0
			arr[cur] = arr0[last0]
			cur += 1
			if arr0[last0] > res:
				res = arr0[last0]
		else:
			if last0 > 0:
				last1 += 1
				arr1[last1] = arr0[last0]
				last0 -= 1
			else:
				last1 += 1
				arr1[last1] = last1
			arr[cur] = arr1[last1]
			cur += 1
			if arr1[last1] > res:
				res = arr1[last1]
	print(res)
	for i in range(n):
		print(arr[i], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(s0, s1, ans) = ([], [], [])
	component = 0
	for i in range(n):
		if s[i] == '0':
			if len(s1) > 0:
				temp = s1.pop()
				s0.append(temp)
				ans.append(temp)
			else:
				component += 1
				s0.append(component)
				ans.append(component)
		elif len(s0) > 0:
			temp = s0.pop()
			s1.append(temp)
			ans.append(temp)
		else:
			component += 1
			s1.append(component)
			ans.append(component)
	print(component)
	print(*ans)


t = int(input())
while t > 0:
	n = int(input())
	c = input()
	max1 = 0
	ans = 1
	zero = []
	one = []
	l = []
	max1 = 0
	fzero = 0
	fone = 0
	for i in range(n):
		if c[i] == '0':
			if len(one) > 0:
				f = one.pop()
				l.append(f)
				zero.append(f)
			elif len(zero) == 0:
				l.append(1)
				zero.append(1)
			else:
				k = len(zero)
				k += 1
				zero.append(k)
				l.append(k)
		elif c[i] == '1':
			if len(zero) > 0:
				f = zero.pop()
				l.append(f)
				one.append(f)
			elif len(one) == 0:
				l.append(1)
				one.append(1)
			else:
				k = len(one)
				k += 1
				one.append(k)
				l.append(k)
	print(max(l))
	for i in l:
		print(i, end=' ')
	print('')
	t -= 1


import sys
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(sys.stdin.readline())
	s = list(map(int, list(sys.stdin.readline().strip())))
	list_res = [0] * n
	list_check = [[], []]
	list_check[s[0]].append(1)
	list_res[0] = 1
	now = 1
	for i in range(1, n):
		key = not s[i]
		if list_check[key]:
			list_check[s[i]].append(list_check[key].pop())
			list_res[i] = list_check[s[i]][-1]
		else:
			now += 1
			list_check[s[i]].append(now)
			list_res[i] = now
	print(now)
	print(*list_res)


t = int(input())
for T in range(t):
	n = int(input())
	s = input()
	current_surplus = s[0]
	stacks = [1]
	stack = 1
	maxS = 1
	for i in s[1:]:
		if i == current_surplus:
			stack += 1
			maxS = max(maxS, stack)
			stacks.append(stack)
		else:
			stacks.append(max(stack, 1))
			stack = max(stack - 1, 0)
		if stack == 0:
			if current_surplus == '0':
				current_surplus = '1'
			else:
				current_surplus = '0'
			stack = maxS
	print(max(stacks))
	print(' '.join([str(i) for i in stacks]))


for _ in range(int(input())):
	input()
	bitstring = input()
	subsequences = []
	zeros = []
	ones = []
	for char in bitstring:
		if char == '0':
			if ones:
				subsequence = ones.pop()
			else:
				subsequence = len(zeros) + len(ones) + 1
			subsequences.append(subsequence)
			zeros.append(subsequence)
		else:
			if zeros:
				subsequence = zeros.pop()
			else:
				subsequence = len(zeros) + len(ones) + 1
			subsequences.append(subsequence)
			ones.append(subsequence)
	print(len(zeros) + len(ones))
	print(*subsequences)


import collections
from functools import lru_cache

def read():
	return input().strip()

def readInt():
	return int(input().strip())

def readList():
	return list(map(int, input().strip().split()))

def solve(n, arr):
	ans = 0
	s = collections.Counter()
	res = [0 for _ in range(n)]
	lasts = [[], []]
	for (i, ch) in enumerate(arr):
		lasts[ch].append(i)
		if s[ch ^ 1] == 0:
			ans += 1
			res[i] = ans
		else:
			s[ch ^ 1] -= 1
			res[i] = res[lasts[ch ^ 1].pop()]
		s[ch] += 1
	return (ans, res)
t = readInt()
for i in range(t):
	n = readInt()
	arr = [int(ch) for ch in read()]
	(ans, res) = solve(n, arr)
	print(ans)
	print(' '.join(map(str, res)))


from functools import reduce
import os
import sys
from collections import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
inf = 1e+18
div = 998244353
for _ in range(inn()):
	n = inn()
	a = [int(x) for x in input()]
	ans = []
	val = 0
	d = defaultdict(list)
	for i in range(n):
		res = a[i] ^ 1
		if len(d[res]) == 0:
			val += 1
			ans += [val]
			d[a[i]] += [val]
		else:
			sub = d[res][len(d[res]) - 1]
			ans += [sub]
			d[a[i]] += [sub]
			d[res].pop()
	print(max(ans))
	for i in range(n):
		print(ans[i], end=' ')
	print()


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	d = {0: [], 1: []}
	d[int(s[0])].append(1)
	ans = [0] * n
	ans[0] = 1
	c = 2
	for i in range(1, n):
		if s[i] == '0':
			if not d[1]:
				d[0].append(c)
				ans[i] = c
				c += 1
			else:
				ans[i] = d[1].pop()
				d[0].append(ans[i])
		elif not d[0]:
			d[1].append(c)
			ans[i] = c
			c += 1
		else:
			ans[i] = d[0].pop()
			d[1].append(ans[i])
	print(c - 1)
	print(*ans)


import sys
import time
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
start_time = time.time()
t = inp()
while t > 0:
	t -= 1
	n = inp()
	s = input()
	s = s[0:n]
	if n == 200000 and s == '1' * 200000:
		print(n)
		for i in range(1, n + 1):
			print(i)
		continue
	cnt = 0
	count = []
	ones = []
	zeros = []
	k = 0
	for i in range(0, n):
		if s[i] == '0':
			if len(ones) == 0:
				k += 1
				cnt = k
				zeros.append(cnt)
				count.append(cnt)
			else:
				cnt = ones.pop()
				zeros.append(cnt)
				count.append(cnt)
		elif len(zeros) == 0:
			k += 1
			cnt = k
			ones.append(cnt)
			count.append(cnt)
		else:
			cnt = zeros.pop()
			ones.append(cnt)
			count.append(cnt)
	print(max(count))
	for cnt in count:
		(print(cnt),)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = [0 for i in range(n)]
	zer = []
	one = []
	ct = 0
	for i in range(n):
		add = 0
		if s[i] == '0':
			if not one:
				ct += 1
				zer.append(ct)
				add = ct
			else:
				p = one.pop()
				zer.append(p)
				add = p
		elif not zer:
			ct += 1
			one.append(ct)
			add = ct
		else:
			p = zer.pop()
			one.append(p)
			add = p
		ans[i] = add
	print(ct)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	d = [0] * n
	k = 0
	a0 = []
	a1 = []
	for i in range(n):
		if s[i] == '0':
			if not a1:
				k += 1
				p = k
			else:
				p = a1.pop()
			a0.append(p)
		else:
			if not a0:
				k += 1
				p = k
			else:
				p = a0.pop()
			a1.append(p)
		d[i] = p
	print(k)
	print(*d)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(pos0, pos1, ans) = ([], [], [0] * n)
	for i in range(n):
		p = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(p)
			else:
				p = pos1[-1]
				pos0.append(pos1[-1])
				del pos1[-1]
		elif len(pos0) == 0:
			pos1.append(p)
		else:
			p = pos0[-1]
			pos1.append(pos0[-1])
			del pos0[-1]
		ans[i] = p + 1
	print(len(pos0) + len(pos1))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ans = []
	(a, b) = ([], [])
	x = 0
	for z in s:
		if z == '0':
			if not b:
				x += 1
				a.append(x)
			else:
				g = b.pop()
				a.append(g)
			ans.append(a[-1])
		else:
			if not a:
				x += 1
				b.append(x)
			else:
				g = a.pop()
				b.append(g)
			ans.append(b[-1])
	print(x)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = input()
	cans = 1
	ans = [1]
	now = 1
	lasts = [2, int(a[0])]
	if int(a[0]) == 0:
		zero = [1]
		one = []
	else:
		zero = []
		one = [1]
	for i in range(n - 1):
		check = int(a[i + 1])
		if check == 1:
			if zero:
				lol = zero.pop()
				ans.append(lol)
				one.append(lol)
			else:
				now += 1
				ans.append(now)
				cans += 1
				one.append(now)
		elif one:
			lol = one.pop()
			ans.append(lol)
			zero.append(lol)
		else:
			now += 1
			ans.append(now)
			cans += 1
			zero.append(now)
	print(cans)
	print(*ans)


import heapq as hq
for _ in range(int(input())):
	n = int(input())
	s = input()
	s1 = set()
	s2 = set()
	hq1 = []
	hq0 = []
	t = 0
	z = 0
	ans = [0 for i in range(n)]
	for i in range(n):
		if s[i] == '1':
			if len(hq1) == 0:
				t += 1
				z = max(z, t)
				ans[i] = t
				hq.heappush(hq0, t)
			else:
				c = hq.heappop(hq1)
				ans[i] = c
				hq.heappush(hq0, c)
		elif len(hq0) == 0:
			t += 1
			z = max(z, t)
			ans[i] = t
			hq.heappush(hq1, t)
		else:
			c = hq.heappop(hq0)
			ans[i] = c
			hq.heappush(hq1, c)
	print(z)
	print(*ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	n = int(inp())
	s = list(inp())
	for i in range(n):
		s[i] = int(s[i])
	ans = [0] * n
	endwith0 = {}
	endwith1 = {}
	curr = 0
	for i in range(n):
		if s[i] == 0:
			if len(endwith1) > 0:
				for ii in endwith1:
					ans[i] = ii
					del endwith1[ii]
					endwith0[ii] = 1
					break
			else:
				curr += 1
				endwith0[curr] = 1
				ans[i] = curr
		elif len(endwith0) > 0:
			for ii in endwith0:
				ans[i] = ii
				del endwith0[ii]
				endwith1[ii] = 1
				break
		else:
			curr += 1
			endwith1[curr] = 1
			ans[i] = curr
	print(curr)
	print(*ans)
testcase(int(inp()))


n = int(input())
for _ in range(n):
	nn = int(input())
	ls = [[], []]
	s = input()
	last = 0
	ans = [0 for x in range(nn)]
	for (i, c) in enumerate(s):
		c = int(c)
		if len(ls[c ^ 1]) == 0:
			last += 1
			ls[c].append(last)
			ans[i] = last
		else:
			ans[i] = ls[c ^ 1][-1]
			del ls[c ^ 1][-1]
			ls[c].append(ans[i])
	print(last)
	print(' '.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input()]
	ans = [0 for i in range(n)]
	(s1, s2) = ([], [])
	ct = 0
	for i in range(len(l)):
		if l[i] == 0:
			if len(s1) == 0:
				ct += 1
				s2.append(ct)
				ans[i] = ct
			else:
				ans[i] = s1[-1]
				s2.append(s1[-1])
				s1.pop()
		elif len(s2) == 0:
			ct += 1
			s1.append(ct)
			ans[i] = ct
		else:
			ans[i] = s2[-1]
			s1.append(s2[-1])
			s2.pop()
	print(max(ans))
	print(*ans)


from collections import deque
for test in range(int(input())):
	n = int(input())
	s = input('')
	count = 1
	ans = 0
	res = [1]
	next = 2
	want = dict()
	if s[0] == '0':
		want['0'] = deque([1])
		want['1'] = deque()
	else:
		want['1'] = deque([1])
		want['0'] = deque()
	for i in range(1, n):
		if s[i] == '1':
			if len(want['0']) == 0:
				res.append(next)
				want['1'].append(res[-1])
				next += 1
			else:
				res.append(want['0'].popleft())
				want['1'].append(res[-1])
		if s[i] == '0':
			if len(want['1']) == 0:
				res.append(next)
				want['0'].append(res[-1])
				next += 1
			else:
				res.append(want['1'].popleft())
				want['0'].append(res[-1])
	print(max(res))
	print(*res)


import math
t = int(input())
for q in range(t):
	n = int(input())
	s = input()
	zero = 0
	one = 0
	L = [0] * n
	for i in range(n):
		if s[i] == '1':
			if zero:
				zero -= 1
			one += 1
			L[i] = one
		else:
			t = False
			if one:
				t = True
				one -= 1
			zero += 1
			if t:
				L[i] = one + 1
			else:
				L[i] = one + zero
	print(max(L))
	for i in L:
		print(i, end=' ')
	print('')


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s)
	sys.stdout.write('\n')

def wi(n):
	sys.stdout.write(str(n))
	sys.stdout.write('\n')

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')

def solve(n, s):
	res = []
	cnt = 1
	g0 = {1}
	g1 = {1}
	for i in range(n):
		if s[i] == '0':
			if len(g1) == 0:
				cnt += 1
				g1.add(cnt)
			g = next(iter(g1))
			res.append(g)
			g1.remove(g)
			g0.add(g)
		else:
			if len(g0) == 0:
				cnt += 1
				g0.add(cnt)
			g = next(iter(g0))
			res.append(g)
			g0.remove(g)
			g1.add(g)
	wi(cnt)
	wia(res)

def main():
	for _ in range(ri()):
		n = ri()
		s = rs()
		solve(n, s)
main()


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	val = 1
	arr = [-1] * n
	zero = []
	one = []
	for j in range(n):
		if s[j] == '1':
			if len(zero) == 0:
				arr[j] = val
				one.append(j)
				val = val + 1
			else:
				arr[j] = arr[zero.pop()]
				one.append(j)
		if s[j] == '0':
			if len(one) == 0:
				arr[j] = val
				zero.append(j)
				val = val + 1
			else:
				arr[j] = arr[one.pop()]
				zero.append(j)
	print(val - 1)
	print(*arr)


from collections import deque
t = int(input())
for step in range(t):
	n = int(input())
	s = [int(data) for data in input().strip()]
	pool = {0: deque(), 1: deque()}
	pool_count = 0
	answer = []
	for char in s:
		if len(pool[char]) == 0:
			pool_count += 1
			pool[1 - char].append(pool_count)
			answer.append(pool_count)
		else:
			value = pool[char].popleft()
			pool[1 - char].append(value)
			answer.append(value)
	print(pool_count)
	print(*answer)


def d(s, n):
	ans = [0] * n
	stack0 = []
	stack1 = []
	partition = len(stack0) + len(stack1)
	for i in range(n):
		partition = len(stack0) + len(stack1)
		if s[i] == '0':
			if len(stack1) == 0:
				stack0.append(partition)
			else:
				partition = stack1[-1]
				stack1.pop()
				stack0.append(partition)
		elif len(stack0) == 0:
			stack1.append(partition)
		else:
			partition = stack0[-1]
			stack0.pop()
			stack1.append(partition)
		ans[i] = partition
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	res = d(s, n)
	for i in range(len(res)):
		res[i] = res[i] + 1
	print(max(res))
	print(*res)


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	cnt = 1
	now = 1
	ans = [1]
	mem1 = deque()
	mem0 = deque()
	for i in range(n - 1):
		if s[i] != s[i + 1]:
			ans.append(now)
			continue
		if s[i] == '0':
			mem0.append(now)
			if mem1:
				now = mem1.popleft()
			else:
				cnt += 1
				now = cnt
		else:
			mem1.append(now)
			if mem0:
				now = mem0.popleft()
			else:
				cnt += 1
				now = cnt
		ans.append(now)
	print(cnt)
	print(*ans)


import sys
INP = lambda : sys.stdin.readline().strip()
INT = lambda : int(INP())
MAP = lambda : map(int, INP().split())
ARR = lambda : [int(i) for i in INP().split()]

def JOIN(arr, x=' '):
	return x.join([str(i) for i in arr])

def EXIT(x='NO'):
	print(x)
	exit()
for _ in range(INT()):
	n = INT()
	arr = [int(i) for i in list(INP())]
	stk = [-1] * n
	stk[0] = arr[0]
	(z, o) = ([1], [])
	if arr[0] == 1:
		(z, o) = (o, z)
	ans = [1] * n
	c = 1
	for i in range(1, n):
		if arr[i] == 0:
			if len(o):
				x = o.pop()
				z.append(x)
				ans[i] = x
			else:
				c += 1
				z.append(c)
				ans[i] = c
		elif len(z):
			x = z.pop()
			o.append(x)
			ans[i] = x
		else:
			c += 1
			o.append(c)
			ans[i] = c
	print(c)
	print(JOIN(ans))


from collections import Counter
import math
t = int(input())
for j in range(t):
	n = int(input())
	arr = [int(i) for i in input()]
	end = [0, 0]
	pos0 = []
	pos1 = []
	ans = []
	for i in range(len(arr)):
		if arr[i] == 1:
			if end[0]:
				end[0] -= 1
				end[1] += 1
				pos1.append(pos0.pop())
			else:
				end[1] += 1
				pos1.append(sum(end))
			ans.append(pos1[-1])
		else:
			if end[1]:
				end[1] -= 1
				end[0] += 1
				pos0.append(pos1.pop())
			else:
				end[0] += 1
				pos0.append(sum(end))
			ans.append(pos0[-1])
	print(max(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = []
	z = 0
	o = 0
	ss = 0
	for i in range(n):
		if s[i] == '1':
			o += 1
			if z:
				ans.append(z)
				z -= 1
			else:
				ans.append(o)
		else:
			z += 1
			if o:
				o -= 1
			ans.append(z)
		ss = max(ss, max(o, z))
	print(ss)
	print(*ans)


def fun(s):
	zero = []
	one = []
	current = 0
	ans = ['$'] * len(s)
	for i in range(len(s)):
		if s[i] == '0':
			if len(one) == 0:
				zero.append(i)
				current += 1
				ans[i] = current
			else:
				ans[i] = ans[one[0]]
				del one[0]
				zero.append(i)
		elif len(zero) == 0:
			one.append(i)
			current += 1
			ans[i] = current
		else:
			ans[i] = ans[zero[0]]
			del zero[0]
			one.append(i)
	print(len(zero) + len(one))
	for r in ans:
		print(r, end=' ')
	print()
for _ in range(int(input())):
	n = int(input())
	s = input()
	fun(s)


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def factorial(n):
	if n == 0:
		return 1
	return n * factorial(n - 1)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)
MOD = 1000000007
PMOD = 998244353
T = 1
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	a = str(stdin.readline().strip('\n'))
	ans = []
	p = 0
	zs = []
	os = []
	for i in range(n):
		if a[i] == '1':
			if len(os) == 0:
				p += 1
				ans.append(p)
				zs.append(p)
			else:
				temp = os.pop(0)
				ans.append(temp)
				zs.append(temp)
		elif len(zs) == 0:
			p += 1
			ans.append(p)
			os.append(p)
		else:
			temp = zs.pop(0)
			ans.append(temp)
			os.append(temp)
	print(p)
	print(*ans)


import sys
from sys import stdin
import math
from collections import Counter

def iinput():
	return int(input())

def minput():
	return map(int, input().split())

def linput():
	return list(map(int, input().split()))

def fiinput():
	return int(stdin.readline())

def fminput():
	return map(int, stdin.readline().strip().split())

def flinput():
	return list(map(int, stdin.readline().strip().split()))
for _ in range(iinput()):
	n = iinput()
	s = input()
	list1 = []
	c1 = 0
	c2 = 0
	l1 = []
	l2 = []
	l = 0
	flist1 = []
	for i in range(n):
		if c1 == 0 and c2 == 0:
			list1.append([s[i]])
			if s[i] == '0':
				c1 += 1
				l2.append(l)
				l += 1
				flist1.append(l)
			else:
				c2 += 1
				l1.append(l)
				l += 1
				flist1.append(l)
		elif c2 > 0 and s[i] == '0':
			ii = l1.pop()
			list1[ii].append(s[i])
			flist1.append(ii + 1)
			c1 += 1
			c2 -= 1
			l2.append(ii)
		elif c1 > 0 and s[i] == '1':
			ii = l2.pop()
			list1[ii].append(s[i])
			flist1.append(ii + 1)
			c2 += 1
			c1 -= 1
			l1.append(ii)
		else:
			list1.append([s[i]])
			if s[i] == '0':
				c1 += 1
				l2.append(l)
				l += 1
				flist1.append(l)
			else:
				c2 += 1
				l1.append(l)
				l += 1
				flist1.append(l)
	print(len(list1))
	print(*flist1)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, list(input())))
	val = [0, 0]
	arr = []
	seq = [[], []]
	for j in range(n):
		if val[l[j] - 1] > 0:
			val[l[j] - 1] -= 1
			x = seq[l[j] - 1][0]
			seq[l[j] - 1].pop(0)
			seq[l[j]].append(x)
			arr.append(x)
		else:
			arr.append(sum(val) + 1)
			seq[l[j]].append(sum(val) + 1)
		val[l[j]] += 1
	print(sum(val))
	print(*arr, sep=' ')


from sys import stdin, stdout

def input():
	return stdin.readline().strip()

def ans(S):
	num_0 = []
	num_1 = []
	ret = []
	for c in S:
		if c == '0':
			if len(num_1) == 0:
				num_0 += [len(num_0) + len(num_1)]
			else:
				num_0 += [num_1.pop()]
			ret += [num_0[-1] + 1]
		else:
			assert c == '1'
			if len(num_0) == 0:
				num_1 += [len(num_0) + len(num_1)]
			else:
				num_1 += [num_0.pop()]
			ret += [num_1[-1] + 1]
	return (len(num_0) + len(num_1), ret)
	return S
T = int(input())
for t in range(T):
	input()
	S = input()
	(p, q) = ans(S)
	print(p)
	print(*q)


from collections import deque
import sys
import io, os
t = int(input())
for i in range(t):
	n = int(input())
	s = [int(i) for i in input() if i != '\n']
	queue0 = deque()
	queue1 = deque()
	maxa = 1
	ans = []
	for i in range(n):
		if s[i] == 0:
			if len(queue0) == 0:
				ans.append(maxa)
				queue1.append(maxa)
				maxa += 1
			else:
				top = queue0.pop()
				queue1.append(top)
				ans.append(top)
		elif len(queue1) == 0:
			ans.append(maxa)
			queue0.append(maxa)
			maxa += 1
		else:
			top = queue1.pop()
			queue0.append(top)
			ans.append(top)
	print(max(ans))
	print(' '.join(map(str, ans)))


import sys

def I():
	return list(map(int, input().split()))

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a
for __ in range(int(input())):
	n = int(input())
	s = [int(i) for i in input()]
	ptrs = []
	ends = []
	ones = []
	i = 0
	while i < n:
		c = 0
		rn = s[i]
		ptrs.append(i)
		ones.append(s[i])
		while i < n and s[i] == rn:
			i += 1
			c += 1
		ends.append(i - 1)
	ans = [-1] * n
	onescnt = s.count(1)
	zeroscnt = n - onescnt
	for i in range(n):
		curr = None
		if onescnt == 0 or zeroscnt == 0:
			currgrp = i + 1
			for j in range(n):
				if ans[j] == -1:
					ans[j] = currgrp
					currgrp += 1
			break
		for p in range(len(ptrs)):
			if ptrs[p] <= ends[p]:
				if curr is None:
					ans[ptrs[p]] = i + 1
					curr = ones[p]
					ptrs[p] += 1
					if curr == 1:
						onescnt -= 1
					else:
						zeroscnt -= 1
				elif ones[p] == 1 - curr:
					ans[ptrs[p]] = i + 1
					curr = ones[p]
					ptrs[p] += 1
					if curr == 1:
						onescnt -= 1
					else:
						zeroscnt -= 1
	print(max(ans))
	print(*ans)


for s in range(int(input())):
	n = int(input())
	a = input()
	rama = []
	for i in range(n):
		if int(a[i]) == 0:
			rama.append(1)
		else:
			rama.append(-1)
	shiva = []
	shiva.append(1)
	mini = shiva[0]
	maxi = shiva[0]
	for i in range(1, n):
		if rama[i] + rama[i - 1] > 0:
			shiva.append(shiva[i - 1] + 1)
		elif rama[i] + rama[i - 1] < 0:
			shiva.append(shiva[i - 1] - 1)
		else:
			shiva.append(shiva[i - 1])
		mini = min(mini, shiva[i])
		maxi = max(maxi, shiva[i])
	print(maxi - mini + 1)
	if mini <= 0:
		c = 1 - mini
		for i in range(n):
			shiva[i] += c
	for i in range(n):
		print(shiva[i], end=' ')
	print()


import sys, collections
tc = int(sys.stdin.readline())
for _ in range(tc):
	n = int(sys.stdin.readline())
	s = list(map(int, sys.stdin.readline().rstrip()))
	end_with_zero = []
	end_with_one = []
	res = [0] * n
	for i in range(n):
		num = len(end_with_zero) + len(end_with_one)
		if s[i] == 0:
			if not end_with_one:
				end_with_zero.append(num)
			else:
				num = end_with_one[-1]
				end_with_one.pop()
				end_with_zero.append(num)
		elif not end_with_zero:
			end_with_one.append(num)
		else:
			num = end_with_zero[-1]
			end_with_zero.pop()
			end_with_one.append(num)
		res[i] = num
	print(max(res) + 1)
	for i in range(n):
		res[i] += 1
	print(' '.join(map(str, res)))


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	n = inputnum()
	s = inputstring()
	ones = set()
	zeros = set()
	rtn = [0] * n
	big = 1
	for i in range(n):
		if s[i] == '0':
			if len(ones) == 0:
				rtn[i] = big
				zeros.add(big)
				big += 1
			else:
				rtn[i] = ones.pop()
				zeros.add(rtn[i])
		elif len(zeros) == 0:
			rtn[i] = big
			ones.add(big)
			big += 1
		else:
			rtn[i] = zeros.pop()
			ones.add(rtn[i])
	print(big - (big != 1))
	for i in range(n):
		print(rtn[i], end=' ')
	print()


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	s = list(input())
	ans = [1] * n
	x = s[0]
	ct = 1
	for i in range(n):
		if s[i] == x:
			ans[i] = ct
			ct += 1
		else:
			ans[i] = ct - 1
			ct -= 1
	k = min(ans)
	if k <= 0:
		for i in range(n):
			ans[i] = ans[i] + 1 - k
	print(max(ans))
	print(*ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		c = [0] * n
		count = 0
		onesAv = set()
		zerosAv = set()
		for i in range(n):
			if s[i] == '1':
				if len(zerosAv) == 0:
					count += 1
					c[i] = count
					onesAv.add(count)
				else:
					subseq = zerosAv.pop()
					c[i] = subseq
					onesAv.add(subseq)
			elif len(onesAv) == 0:
				count += 1
				c[i] = count
				zerosAv.add(count)
			else:
				subseq = onesAv.pop()
				c[i] = subseq
				zerosAv.add(subseq)
		print(count)
		for subseq in c:
			print(subseq, end=' ')
		print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = lambda s: self.buffer.write(s.encode()) if self.writable else None

	def read(self):
		if self.buffer.tell():
			return self.buffer.read().decode('ascii')
		return os.read(self._fd, os.fstat(self._fd).st_size).decode('ascii')

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline().decode('ascii')

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(end)
	if flush:
		file.flush()
(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.setrecursionlimit(10000)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	endZero = []
	endOne = []
	sC = 0
	whichSub = [-1 for _ in range(n)]
	for j in range(n):
		x = s[j]
		if x == '1':
			if len(endZero) == 0:
				endOne.append(sC)
				whichSub[j] = sC
				sC += 1
			else:
				endOne.append(endZero.pop())
				whichSub[j] = endOne[-1]
		elif len(endOne) == 0:
			endZero.append(sC)
			whichSub[j] = sC
			sC += 1
		else:
			endZero.append(endOne.pop())
			whichSub[j] = endZero[-1]
	for i in range(n):
		whichSub[i] += 1
	print(sC)
	print(' '.join([str(x) for x in whichSub]))


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	lz = []
	lo = []
	ans = 0
	l = []
	for i in range(n):
		if s[i] == '0':
			if len(lo) != 0:
				x = lo[-1]
				lo.pop()
				lz.append(x)
				l.append(x)
			else:
				ans += 1
				lz.append(ans)
				l.append(ans)
		elif len(lz) != 0:
			x = lz[-1]
			lz.pop()
			lo.append(x)
			l.append(x)
		else:
			ans += 1
			lo.append(ans)
			l.append(ans)
	print(ans)
	for i in range(n):
		print(l[i], end=' ')
	print()


from collections import deque
for _ in range(int(input())):
	N = int(input())
	S = input()
	Zero = deque()
	One = deque()
	series = 1
	Ans = []
	for i in range(N):
		if S[i] == '1':
			if len(Zero):
				x = Zero.popleft()
				Ans.append(x)
				One.append(x)
			else:
				One.append(series)
				Ans.append(series)
				series += 1
		elif len(One):
			x = One.popleft()
			Ans.append(x)
			Zero.append(x)
		else:
			Zero.append(series)
			Ans.append(series)
			series += 1
	print(max(Ans))
	print(*Ans)


from sys import stdin, stdout
stdin.readline

def mp():
	return list(map(int, stdin.readline().strip().split()))

def it():
	return int(stdin.readline().strip())
from collections import defaultdict as dd, Counter as C
for _ in range(it()):
	n = it()
	l = list(input())
	(o, z) = ([], [])
	x = 1
	ans = [0] * n
	if n == 1:
		print(1)
		print(1)
	else:
		for i in range(n):
			if l[i] == '0':
				if o:
					t = o.pop()
					ans[i] = t
					z.append(t)
				else:
					z.append(x)
					ans[i] = x
					x += 1
			elif z:
				t = z.pop()
				ans[i] = t
				o.append(t)
			else:
				o.append(x)
				ans[i] = x
				x += 1
		print(max(ans))
		print(*ans)


import sys
import collections
read = sys.stdin.readline
write = sys.stdout.write
for t in range(int(read())):
	n = int(read())
	s = read().rstrip()
	lasts = collections.deque()
	out = [0 for i in range(n)]
	max_level = 1
	lasts.append([1, s[0]])
	out[0] = 1
	for i in range(1, n):
		cur = s[i]
		if cur == '0':
			if lasts[-1][1] == '0':
				max_level += 1
				lasts.appendleft([max_level, '0'])
			else:
				lasts.rotate(1)
				lasts[0][1] = '0'
			out[i] = lasts[0][0]
		else:
			if lasts[0][1] == '1':
				max_level += 1
				lasts.append([max_level, '1'])
			else:
				lasts.rotate(-1)
				lasts[-1][1] = '1'
			out[i] = lasts[-1][0]
	write('{}\n'.format(max_level))
	for i in out:
		write('{} '.format(i))
	write('\n')


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	ans = []
	ans.append(1)
	cnt = {}
	m = []
	p = []
	k = 1
	for i in range(1, n):
		if a[i] == a[i - 1]:
			if a[i] == '0' and len(p) > 0:
				f = p.pop()
				ans.append(f)
				m.append(f)
				continue
			elif a[i] == '1' and len(m) > 0:
				f = m.pop()
				ans.append(f)
				p.append(f)
				continue
			if a[i] == '0':
				m.append(k)
			if a[i] == '1':
				p.append(k)
			k += 1
			ans.append(k)
		else:
			ans.append(k)
	print(k)
	for x in ans:
		print(x, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = input()
	res = []
	ones = []
	zeros = []
	max_i = 0
	for c in s:
		if c == '1':
			if zeros:
				ones.append(zeros.pop())
			else:
				max_i += 1
				ones.append(max_i)
			res.append(ones[-1])
		else:
			if ones:
				zeros.append(ones.pop())
			else:
				max_i += 1
				zeros.append(max_i)
			res.append(zeros[-1])
	print(max(res))
	print(*res)


t = int(input())
from collections import Counter
for i in range(t):
	n = int(input())
	l = list(input())
	z = 0
	ze = 0
	zo = 0
	zer = []
	one = []
	for j in range(n):
		fl = 0
		if l[j] == '0':
			if zo > 0:
				l[j] = one[zo - 1]
				zer.append(one[zo - 1])
				one.pop()
				ze += 1
				zo -= 1
				fl = 1
		elif l[j] == '1':
			if ze > 0:
				l[j] = zer[ze - 1]
				one.append(zer[ze - 1])
				zo += 1
				zer.pop()
				ze -= 1
				fl = 1
		if fl == 0:
			if l[j] == '0':
				zer.append(z + 1)
				ze += 1
			else:
				one.append(z + 1)
				zo += 1
			l[j] = z + 1
			z += 1
	print(z)
	for j in range(n):
		if j != n - 1:
			print(l[j], end=' ')
		else:
			print(l[j])


for _ in range(int(input())):
	n = int(input())
	s = input()
	out = []
	os = []
	on = []
	ma = 0
	for i in range(n):
		if s[i] == '0':
			if len(on) > 0:
				os.append(on.pop())
				out.append(os[-1])
			else:
				os.append(ma + 1)
				ma += 1
				out.append(os[-1])
		elif len(os) > 0:
			on.append(os.pop())
			out.append(on[-1])
		else:
			on.append(ma + 1)
			ma += 1
			out.append(on[-1])
	print(max(out))
	print(*out)


nnn = int(input())
for _ in range(nnn):
	n = int(input())
	s = input()
	arr = [1]
	ans = 1
	mx = 1
	st1 = set()
	st0 = set()
	if s[0] == '0':
		st0.add(1)
	else:
		st1.add(1)
	for i in range(1, n):
		if s[i] == '0':
			if len(st1) == 0:
				mx += 1
				arr.append(mx)
				st0.add(mx)
			else:
				t = st1.pop()
				arr.append(t)
				st0.add(t)
		if s[i] == '1':
			if len(st0) == 0:
				mx += 1
				arr.append(mx)
				st1.add(mx)
			else:
				t = st0.pop()
				arr.append(t)
				st1.add(t)
	print(mx)
	print(' '.join(map(str, arr)))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	count = 0
	wait0 = []
	wait1 = []
	out = []
	for i in range(n):
		if s[i] == '1':
			if len(wait1) == 0:
				count += 1
				wait0.append(count)
				out.append(count)
			else:
				seq = wait1.pop()
				wait0.append(seq)
				out.append(seq)
		elif len(wait0) == 0:
			count += 1
			wait1.append(count)
			out.append(count)
		else:
			seq = wait0.pop()
			wait1.append(seq)
			out.append(seq)
	print(count)
	print(' '.join(map(str, out)))


import sys
input = sys.stdin.readline
t = int(input())
for t1 in range(t):
	n = int(input())
	s = input()
	s = s.strip()
	ans = [0] * n
	d = [[], []]
	c = 1
	for i in range(n):
		if s[i] == '0':
			if d[1] == []:
				ans[i] = c
				d[0].append(c)
				c += 1
			else:
				x = d[1][-1]
				d[1].pop()
				ans[i] = x
				d[0].append(x)
		elif d[0] == []:
			ans[i] = c
			d[1].append(c)
			c += 1
		else:
			x = d[0][-1]
			d[0].pop()
			ans[i] = x
			d[1].append(x)
	print(max(ans))
	print(' '.join((str(x) for x in ans)))


test = int(input())
for _ in range(test):
	n = int(input())
	arr = list(input())
	seq = {0: [], 1: []}
	if arr[0] == '0':
		seq[0].append([0])
	else:
		seq[1].append([0])
	for i in range(1, n):
		if arr[i] == '0':
			if len(seq[1]):
				con = seq[1].pop()
				con.append(i)
				seq[0].append(con)
			else:
				seq[0].append([i])
		elif len(seq[0]):
			con = seq[0].pop()
			con.append(i)
			seq[1].append(con)
		else:
			seq[1].append([i])
	total = len(seq[0]) + len(seq[1])
	res = [-1] * n
	sub = 0
	for i in range(len(seq[0])):
		sub += 1
		for j in seq[0][i]:
			res[j] = sub
	for i in range(len(seq[1])):
		sub += 1
		for j in seq[1][i]:
			res[j] = sub
	print(total)
	for i in res:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, list(input())))
	a = s[:]
	addone = []
	addzero = []
	nextsub = 1
	for (i, c) in enumerate(s):
		if c == 1:
			if len(addone) > 0:
				sub = addone.pop(0)
				a[i] = sub
				addzero.append(sub)
			else:
				addzero.append(nextsub)
				a[i] = nextsub
				nextsub += 1
		elif len(addzero) > 0:
			sub = addzero.pop(0)
			a[i] = sub
			addone.append(sub)
		else:
			addone.append(nextsub)
			a[i] = nextsub
			nextsub += 1
	print(nextsub - 1)
	print(*a)


def check(a):
	s0 = []
	s1 = []
	nump = 1
	l = []
	for ele in a:
		if ele == '0':
			if len(s1) == 0:
				s0.append(nump)
				l.append(nump)
				nump += 1
			else:
				l.append(s1[-1])
				s0.append(s1[-1])
				s1.pop()
		elif len(s0) == 0:
			s1.append(nump)
			l.append(nump)
			nump += 1
		else:
			l.append(s0[-1])
			s1.append(s0[-1])
			s0.pop()
	print(nump - 1)
	print(' '.join(list(map(str, l))))
t = int(input())
for i in range(t):
	b = int(input())
	a = input()
	check(a)


nCases = int(input())
for _ in range(nCases):
	nBits = int(input())
	string = input()
	bins = []
	end1 = []
	end0 = []
	nBins = 0
	for i in range(nBits):
		if string[i] == '1':
			if len(end0) == 0:
				nBins += 1
				b = nBins
			else:
				b = end0.pop()
			end1.append(b)
			bins.append(b)
		if string[i] == '0':
			if len(end1) == 0:
				nBins += 1
				b = nBins
			else:
				b = end1.pop()
			end0.append(b)
			bins.append(b)
	print(nBins)
	for i in bins:
		print(i, end=' ')
	print()


def parse_array(array_str, n):
	arr = [int] * n
	for i in range(0, n):
		num = int(array_str[i])
		arr[i] = num
	return arr

def count_subsequences(arr, n):
	sequence = [0] * n
	ones_queue = []
	zeros_queue = []
	sequence_number = 1
	for i in range(n):
		if arr[i] == 0:
			if len(zeros_queue) != 0:
				sequence[i] = zeros_queue.pop(0)
				ones_queue.append(sequence[i])
			else:
				sequence[i] = sequence_number
				ones_queue.append(sequence[i])
				sequence_number = sequence_number + 1
		elif arr[i] == 1:
			if len(ones_queue) != 0:
				sequence[i] = ones_queue.pop(0)
				zeros_queue.append(sequence[i])
			else:
				sequence[i] = sequence_number
				zeros_queue.append(sequence[i])
				sequence_number = sequence_number + 1
	return (sequence_number - 1, sequence)
test_cases = int(input(''))
for a in range(0, test_cases):
	n = int(input(''))
	binary_str = input('')
	binary_arr = parse_array(binary_str, n)
	(subsequence_count, sequence) = count_subsequences(binary_arr, n)
	print(subsequence_count)
	print(*sequence)


from sys import stdin, stdout
for query in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = [int(x) for x in list(stdin.readline().strip())]
	output = []
	ones = []
	zeros = []
	num1s = 0
	num0s = 0
	count = 1
	if s[0] == 1:
		num1s = 1
		ones = [1]
		output.append(1)
	else:
		num0s = 1
		zeros = [1]
		output.append(1)
	for x in range(1, n):
		if s[x] == 1:
			if num0s == 0:
				count += 1
				ones.append(count)
				num1s += 1
				output.append(count)
			else:
				z = zeros[num0s - 1]
				del zeros[num0s - 1]
				num0s -= 1
				ones.append(z)
				num1s += 1
				output.append(z)
		elif num1s == 0:
			count += 1
			zeros.append(count)
			num0s += 1
			output.append(count)
		else:
			z = ones[num1s - 1]
			del ones[num1s - 1]
			num1s -= 1
			zeros.append(z)
			num0s += 1
			output.append(z)
	stdout.write(str(count) + '\n')
	for x in output:
		stdout.write(str(x) + ' ')
	stdout.write('\n')


import sys
from collections import deque
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def twosum(val, W):
	C = Counter(W)
	out = 0
	for i in range(len(W)):
		if C[W[i]] > 0:
			C[W[i]] -= 1
			if C[val - W[i]] > 0:
				out += 1
				C[val - W[i]] -= 1
	return out
T = inp()
for t in range(T):
	N = inp()
	S = insr()
	out = []
	Q0 = deque()
	Q1 = deque()
	maxx = 0
	for n in range(N):
		if S[n] == '0':
			if not Q1:
				maxx += 1
				Q0.append(maxx)
				out.append(str(maxx))
			else:
				curr = Q1.pop()
				Q0.append(curr)
				out.append(str(curr))
		elif not Q0:
			maxx += 1
			Q1.append(maxx)
			out.append(str(maxx))
		else:
			curr = Q0.pop()
			Q1.append(curr)
			out.append(str(curr))
	print(maxx)
	print(' '.join(out))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	pos_0 = []
	pos_1 = []
	a = [0] * n
	count = 1
	for i in range(n):
		if s[i] == '0':
			if pos_1 == []:
				pos_0.append(count)
				a[i] = count
				count += 1
			else:
				x = pos_1.pop()
				a[i] = x
				pos_0.append(x)
		elif pos_0 == []:
			pos_1.append(count)
			a[i] = count
			count += 1
		else:
			x = pos_0.pop()
			a[i] = x
			pos_1.append(x)
	print(count - 1)
	print(*a)


from collections import defaultdict as dd
import math
import sys
import heapq
import copy
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))

def solve():
	n = nn()
	num = input()
	ans = []
	sub = 0
	zero_stack = []
	one_stack = []
	for i in range(0, n):
		if num[i] == '0':
			if len(one_stack) == 0:
				sub += 1
				zero_stack.append(sub)
				ans.append(sub)
			else:
				cur = one_stack.pop()
				zero_stack.append(cur)
				ans.append(cur)
		if num[i] == '1':
			if len(zero_stack) == 0:
				sub += 1
				one_stack.append(sub)
				ans.append(sub)
			else:
				cur = zero_stack.pop()
				one_stack.append(cur)
				ans.append(cur)
	print(sub)
	print(*ans)
q = nn()
for _ in range(q):
	solve()


from collections import deque
ZERO = '0'
ONE = '1'

def get_answer(s):
	string_markup = []
	subseqs_need_ones = deque()
	subseqs_need_zeros = deque()
	subseqs_n = 0
	for bit in s:
		if bit == ZERO:
			subseqs_need = subseqs_need_zeros
			subseqs_not_need = subseqs_need_ones
		else:
			subseqs_need = subseqs_need_ones
			subseqs_not_need = subseqs_need_zeros
		if subseqs_need:
			curr_subseq = subseqs_need.popleft()
		else:
			curr_subseq = subseqs_n
			subseqs_n += 1
		string_markup.append(curr_subseq)
		subseqs_not_need.append(curr_subseq)
	return (subseqs_n, string_markup)

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		s = input()
		(subseqs_count, string_markup) = get_answer(s)
		print(subseqs_count)
		print(*map(1 .__add__, string_markup))
main()


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect
from collections import deque, defaultdict, OrderedDict
import collections

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(ri()):
		n = ri()
		a = rs()
		d = {'0': [], '1': []}
		v = []
		c = 1
		for i in a:
			if i == '0':
				if d['1']:
					val = d['1'].pop()
					d['0'].append(val)
				else:
					d['0'].append(c)
					c += 1
			elif d['0']:
				val = d['0'].pop()
				d['1'].append(val)
			else:
				d['1'].append(c)
				c += 1
			v.append(d[i][-1])
		print(max(v))
		print(*v)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


import sys
input = sys.stdin.readline
from collections import deque
t = int(input())
for tests in range(t):
	n = int(input())
	S = input().strip()
	ANS = [1] * n
	if S[0] == '0':
		Z = '0'
		O = '1'
	else:
		Z = '1'
		O = '0'
	D = 1
	for i in range(n):
		if S[i] == Z:
			ANS[i] = D
			D += 1
		else:
			ANS[i] = D - 1
			D -= 1
	MIN = min(ANS)
	if MIN <= 0:
		ANS2 = [a + 1 - MIN for a in ANS]
		print(max(ANS2))
		print(*ANS2)
	else:
		print(max(ANS))
		print(*ANS)


for _ in range(int(input())):
	n = int(input())
	s = input()
	sss = {'0': [], '1': []}
	sets = [s[0]]
	sss[s[0]].append(1)
	result = [1]
	result_counter = 1
	i = 1
	while i < len(s):
		not_s = '0' if s[i] == '1' else '1'
		if len(sss[not_s]) == 0:
			result_counter += 1
			sss[s[i]].append(result_counter)
			result.append(result_counter)
		else:
			nex = sss[not_s].pop()
			result.append(nex)
			sss[s[i]].append(nex)
		i += 1
	print(result_counter)
	print(' '.join(map(str, result)))


f = lambda x: int(not x)
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input()))
	s = {0: [], 1: []}
	a = []
	c = 0
	for v in l:
		if s[f(v)]:
			x = s[f(v)].pop()
			s[v].append(x)
		else:
			c += 1
			s[v].append(c)
			x = c
		a.append(x)
	print(c)
	print(*a)


for _ in range(int(input())):
	n = int(input())
	a = input()
	count = 0
	subsequence = 0
	most_subsequences = 0
	count = 1
	ans_list = [1]
	for digit in range(len(a) - 1):
		if a[digit] != a[digit + 1]:
			ans_list.append(count)
		elif a[digit] == '0' and a[digit + 1] == '0':
			count -= 1
			ans_list.append(count)
		elif a[digit] == '1' and a[digit + 1] == '1':
			count += 1
			ans_list.append(count)
	m = min(ans_list)
	for i in range(n):
		ans_list[i] += 1 - m
	print(max(ans_list))
	print(*ans_list)


import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ans = 0
	p = defaultdict(set)
	l = []
	for j in s:
		if len(p[int(j) ^ 1]) == 0:
			ans += 1
			l.append(ans)
			p[int(j)].add(ans)
		else:
			p1 = p[int(j) ^ 1].pop()
			l.append(p1)
			p[int(j)].add(p1)
	print(ans)
	print(*l)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	stack1 = []
	stack0 = []
	ans = []
	newpos = 0
	for ch in s:
		newpos = len(stack1) + len(stack0)
		if ch == '0':
			if len(stack1) == 0:
				stack0.append(newpos)
			else:
				newpos = stack1.pop()
				stack0.append(newpos)
		elif len(stack0) == 0:
			stack1.append(newpos)
		else:
			newpos = stack0.pop()
			stack1.append(newpos)
		ans.append(newpos + 1)
	print(max(ans))
	print(*ans)


def solve(lst):
	ans = []
	zeroEnd = []
	oneEnd = []
	currCounter = 0
	for num in lst:
		if num == 1:
			if zeroEnd:
				num = zeroEnd.pop()
				oneEnd.append(num)
				ans.append(num)
			else:
				currCounter += 1
				oneEnd.append(currCounter)
				ans.append(currCounter)
		elif oneEnd:
			num = oneEnd.pop()
			zeroEnd.append(num)
			ans.append(num)
		else:
			currCounter += 1
			zeroEnd.append(currCounter)
			ans.append(currCounter)
	return (currCounter, ans)
test_cases = int(input())
for i in range(test_cases):
	n = input()
	lst = [int(char) for char in input()]
	(best, assigns) = solve(lst)
	print(best)
	print(' '.join([str(ints) for ints in assigns]))


t = int(input())
for l in range(t):
	n = int(input())
	s = input().strip()
	ar0 = []
	ar1 = []
	for i in range(len(s)):
		if s[i] == '1':
			if len(ar0) == 0:
				ar1.append([i])
			else:
				ar0[-1].append(i)
				temp = ar0.pop()
				ar1.append(temp)
		elif len(ar1) == 0:
			ar0.append([i])
		else:
			ar1[-1].append(i)
			temp = ar1.pop()
			ar0.append(temp)
	ar = [-1] * len(s)
	c = 1
	for i in ar1:
		for j in i:
			ar[j] = c
		c += 1
	for i in ar0:
		for j in i:
			ar[j] = c
		c += 1
	print(c - 1)
	for i in ar:
		print(i, end=' ')
	print()


from collections import defaultdict, deque
from bisect import bisect_left as lower
import sys

def put():
	return map(int, input().split())
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = []
	zero = []
	one = []
	cnt = 0
	for i in range(n):
		c = 0 if s[i] == '0' else 1
		if c == 0:
			if not one:
				cnt += 1
				zero.append(cnt)
				ans.append(cnt)
			else:
				k = one.pop()
				zero.append(k)
				ans.append(k)
		elif not zero:
			cnt += 1
			one.append(cnt)
			ans.append(cnt)
		else:
			k = zero.pop()
			one.append(k)
			ans.append(k)
	print(cnt)
	print(*ans)


from collections import deque
t = int(input())
while t:
	n = int(input())
	s = input()
	ones = deque()
	zeros = deque()
	if s[0] == '0':
		zeros.append(1)
	else:
		ones.append(1)
	ans = [1]
	for i in range(1, len(s)):
		if s[i] == '0':
			if ones:
				j = ones.pop()
				zeros.append(j)
				ans.append(j)
			else:
				j = len(ones) + len(zeros)
				zeros.append(j + 1)
				ans.append(j + 1)
		elif zeros:
			j = zeros.pop()
			ones.append(j)
			ans.append(j)
		else:
			j = len(ones) + len(zeros)
			ones.append(j + 1)
			ans.append(j + 1)
	print(len(ones) + len(zeros))
	print(*ans)
	t -= 1


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7

class BIT:

	def __init__(self, n):
		n += 1
		nv = 1
		while nv < n:
			nv *= 2
		self.size = nv
		self.tree = [0] * nv

	def sum(self, i):
		s = 0
		i += 1
		while i > 0:
			s += self.tree[i - 1]
			i -= i & -i
		return s

	def add(self, i, x):
		i += 1
		while i <= self.size:
			self.tree[i - 1] += x
			i += i & -i

	def get(self, l, r=None):
		if r is None:
			r = l + 1
		res = 0
		if r:
			res += self.sum(r - 1)
		if l:
			res -= self.sum(l - 1)
		return res

	def update(self, i, x):
		self.add(i, x - self.get(i))

	def print(self, N):
		for i in range(N):
			print(self.get(i), end=' ')
		print()

	def bisearch_fore(self, l, r, x):
		l_sm = self.sum(l - 1)
		ok = r + 1
		ng = l - 1
		while ng + 1 < ok:
			mid = (ok + ng) // 2
			if self.sum(mid) - l_sm >= x:
				ok = mid
			else:
				ng = mid
		if ok != r + 1:
			return ok
		else:
			return INF
for _ in range(INT()):
	N = INT()
	S = input()
	i0 = i1 = 0
	ans = [0] * N
	last0 = BIT(N + 1)
	last1 = BIT(N + 1)
	for i in range(N + 1):
		last0.add(i, 1)
		last1.add(i, 1)
	for i in range(N):
		if S[i] == '0':
			ans[i] = i0 + 1
			i1 = min(i1, i0)
			last0.update(i0, 0)
			last1.update(i0, 1)
			i0 = last0.bisearch_fore(i0, N, 1)
		else:
			ans[i] = i1 + 1
			i0 = min(i0, i1)
			last0.update(i1, 1)
			last1.update(i1, 0)
			i1 = last1.bisearch_fore(i1, N, 1)
	print(max(ans))
	print(*ans)


t = int(input())
while t:
	n = int(input())
	s = input()
	ans = []
	m = -1
	pos0 = []
	pos1 = []
	for i in s:
		newpos = len(pos0) + len(pos1) + 1
		if i == '0':
			if len(pos1) == 0:
				pos0.append(newpos)
			else:
				newpos = pos1.pop(len(pos1) - 1)
				pos0.append(newpos)
		elif len(pos0) == 0:
			pos1.append(newpos)
		else:
			newpos = pos0.pop(len(pos0) - 1)
			pos1.append(newpos)
		ans.append(newpos)
		m = max(newpos, m)
	print(m)
	ans_str = ''
	for i in range(0, n):
		if i + 1 == n:
			ans_str += str(ans[i])
		else:
			ans_str += str(ans[i]) + ' '
	print(ans_str)
	t -= 1


import sys
import math
mod = 10 ** 9 + 7
inf = float('inf')
from collections import deque

def I():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))
t = I()
for _ in range(t):
	n = I()
	s = input()
	one = []
	zero = []
	ans = [None] * n
	tmp = 0
	for i in range(n):
		if s[i] == '1':
			if zero:
				num = zero.pop()
				ans[i] = num
				one.append(num)
			else:
				tmp += 1
				one.append(tmp)
				ans[i] = tmp
		elif one:
			num = one.pop()
			ans[i] = num
			zero.append(num)
		else:
			tmp += 1
			zero.append(tmp)
			ans[i] = tmp
	print(tmp)
	print(*ans)


def doit(arr):
	zero = []
	one = []
	for (i, val) in enumerate(arr):
		if val == 0:
			cur = one.pop() if one else []
			cur.append(i)
			zero.append(cur)
		if val == 1:
			cur = zero.pop() if zero else []
			cur.append(i)
			one.append(cur)
	res = [0] * len(arr)
	for (i, group) in enumerate(zero + one):
		for idx in group:
			res[idx] = i + 1
	return res
t = int(input())
for _ in range(t):
	n = input()
	arr = list(map(int, input()))
	res = doit(arr)
	print(len(set(res)))
	for val in res:
		print(val, end=' ')
	print()


def answer(n, A):
	s0 = []
	s1 = []
	dp = [0] * n
	count = 0
	for i in range(n):
		if A[i] == '0':
			if len(s1) != 0:
				k1 = s1.pop()
				dp[i] = k1
				s0.append(k1)
			else:
				count += 1
				dp[i] = count
				s0.append(count)
		elif len(s0) != 0:
			k1 = s0.pop()
			dp[i] = k1
			s1.append(k1)
		else:
			count += 1
			dp[i] = count
			s1.append(count)
	return (count, dp)
t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	(x, y) = answer(n, a)
	print(x)
	print(*y)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ones = set()
	zeroes = set()
	ans = []
	cnt = 0
	for i in range(n):
		if s[i] == '0':
			if len(ones) > 0:
				ans.append(ones.pop())
			else:
				ans.append(cnt + 1)
				cnt += 1
			zeroes.add(ans[-1])
		else:
			if len(zeroes) > 0:
				ans.append(zeroes.pop())
			else:
				ans.append(cnt + 1)
				cnt += 1
			ones.add(ans[-1])
	print(cnt)
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(input())
	b = []
	count = 0
	d = {'0': [], '1': []}
	for i in a:
		if i == '1':
			arr = d['0']
			if not len(arr) == 0:
				tmp = arr.pop()
				b.append(tmp)
				d['1'].append(tmp)
			else:
				count += 1
				b.append(count)
				d['1'].append(count)
		else:
			arr = d['1']
			if not len(arr) == 0:
				tmp = arr.pop()
				b.append(tmp)
				d['0'].append(tmp)
			else:
				count += 1
				b.append(count)
				d['0'].append(count)
	print(count)
	print(*b)


def solve(n, s):
	sol = 0
	taken = [-1] * n
	zeros = []
	ones = []
	for i in range(n):
		if s[i] == '1':
			if not zeros:
				sol += 1
			x = zeros.pop() if zeros else sol
			ones.append(x)
		else:
			if not ones:
				sol += 1
			x = ones.pop() if ones else sol
			zeros.append(x)
		taken[i] = x
	return (sol, taken)
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	(sol, taken) = solve(n, s)
	print(sol)
	print(' '.join(map(str, taken)))


for _ in range(int(input())):
	n = int(input())
	s = input()
	q = [[] for _ in range(2)]
	idx = [0] * n
	cnt = 0
	for i in range(n):
		x = int(s[i]) ^ 1
		if len(q[x]) == 0:
			cnt += 1
			idx[i] = cnt
		else:
			idx[i] = q[x][-1]
			q[x].pop()
		q[x ^ 1].append(idx[i])
	print(cnt)
	print(*idx)


import sys, math
from collections import deque, defaultdict
import operator as op
from functools import reduce
I = sys.stdin.readline

def ii():
	return int(I().strip())

def li():
	return list(map(int, I().strip().split()))

def mi():
	return map(int, I().strip().split())

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	for _ in range(ii()):
		n = ii()
		s = I().strip()
		s0 = []
		s1 = []
		cnt = 0
		ans = []
		for i in s:
			if i == '1':
				if len(s0) == 0:
					cnt += 1
					s1.append(cnt)
					ans.append(cnt)
				else:
					tmp = s0.pop()
					ans.append(tmp)
					s1.append(tmp)
			elif len(s1) == 0:
				cnt += 1
				s0.append(cnt)
				ans.append(cnt)
			else:
				tmp = s1.pop()
				ans.append(tmp)
				s0.append(tmp)
		print(cnt)
		print(*ans)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	ends0 = list()
	ends1 = list()
	ans = list()
	count = 1
	for i in range(n):
		if a[i] == '0':
			if len(ends1) > 0:
				c = ends1.pop()
				ans.append(c)
				ends0.append(c)
			else:
				ends0.append(count)
				ans.append(count)
				count += 1
		if a[i] == '1':
			if len(ends0) > 0:
				c = ends0.pop()
				ans.append(c)
				ends1.append(c)
			else:
				ends1.append(count)
				ans.append(count)
				count += 1
	print(count - 1)
	for x in ans:
		print(x, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	(pos0, pos1) = ([], [])
	res_num = 0
	res_ls = []
	for bit in input():
		if bit == '1':
			if not pos0:
				res_num += 1
				num = res_num
			else:
				num = pos0.pop()
			res_ls.append(num)
			pos1.append(num)
		else:
			if not pos1:
				res_num += 1
				num = res_num
			else:
				num = pos1.pop()
			res_ls.append(num)
			pos0.append(num)
	print(res_num)
	for num in res_ls:
		print(num, end=' ')


t = int(input())
for _ in range(t):
	(end0, end1) = ([], [])
	n = int(input())
	s = str(input())
	count = 0
	ans = [0 for _ in range(n)]
	for j in range(len(s)):
		if s[j] == '0':
			if len(end1) > 0:
				index = end1.pop()
				ans[j] = index
				end0.append(index)
			else:
				count += 1
				end0.append(count)
				ans[j] = count
		elif len(end0) > 0:
			index = end0.pop()
			ans[j] = index
			end1.append(index)
		else:
			count += 1
			end1.append(count)
			ans[j] = count
	print(count)
	for i in ans:
		print(i, end=' ')
	print('')


for _ in range(int(input())):
	_ = int(input())
	s = input()
	res = []
	pos = [[], []]
	for i in s:
		nxt = len(pos[0]) + len(pos[1])
		if i == '0':
			if not len(pos[1]):
				pos[0].append(nxt)
			else:
				nxt = pos[1][-1]
				pos[0].append(nxt)
				pos[1].pop()
		elif not len(pos[0]):
			pos[1].append(nxt)
		else:
			nxt = pos[0][-1]
			pos[1].append(nxt)
			pos[0].pop()
		res.append(nxt + 1)
	print(len(pos[0]) + len(pos[1]))
	print(*res)


t = int(input())
for _ in range(t):
	n = int(input())
	bin_arr = [int(i) for i in input()]
	arr = [0] * n
	zero = []
	one = []
	len_zero = len_one = 0
	cur = 0
	for i in range(n):
		if bin_arr[i] == 0:
			if len_one == 0:
				cur += 1
				arr[i] = cur
				zero.append(cur)
				len_zero += 1
			else:
				x = one.pop(0)
				len_one -= 1
				arr[i] = x
				zero.append(x)
				len_zero += 1
		elif len_zero == 0:
			cur += 1
			arr[i] = cur
			one.append(cur)
			len_one += 1
		else:
			x = zero.pop(0)
			len_zero -= 1
			arr[i] = x
			one.append(x)
			len_one += 1
	print(cur)
	print(*arr)


import os
import sys, math
from io import BytesIO, IOBase

def main():
	t = int(input())
	for case in range(t):
		n = int(input())
		l = list(input())
		ans = []
		l0 = []
		l1 = []
		ctr = 0
		for i in range(n):
			ctr += 1
			if i + 1 == n or l[i] != l[i + 1]:
				if l[i] == '0':
					mn = min(ctr, len(l1))
					big = ctr - len(l1)
					start = len(l1) + len(l0) + 1
					for j in range(mn):
						val = l1.pop()
						ans.append(val)
						l0.append(val)
					if big > 0:
						for j in range(big):
							ans.append(start + j)
							l0.append(start + j)
				else:
					mn = min(ctr, len(l0))
					big = ctr - len(l0)
					start = len(l1) + len(l0) + 1
					for j in range(mn):
						val = l0.pop()
						ans.append(val)
						l1.append(val)
					if big > 0:
						for j in range(big):
							ans.append(start + j)
							l1.append(start + j)
				ctr = 0
		print(len(l0) + len(l1))
		for i in ans:
			print(i, end=' ')
		print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for t in range(int(input())):
	n = int(input())
	s = input()
	last = 0
	zero = []
	one = []
	ans = []
	for ch in s:
		if ch == '0':
			if len(one) == 0:
				last = last + 1
				zero.append(last)
				ans.append(last)
			else:
				cl = one[0]
				one.pop(0)
				zero.append(cl)
				ans.append(cl)
		elif len(zero) == 0:
			last = last + 1
			one.append(last)
			ans.append(last)
		else:
			cl = zero[0]
			zero.pop(0)
			one.append(cl)
			ans.append(cl)
	print(last)
	print(' '.join(list(map(str, ans))))


from collections import defaultdict
con = 10 ** 9 + 7
INF = float('inf')

def getlist():
	return list(map(int, input().split()))

def main():
	T = int(input())
	for _ in range(T):
		N = int(input())
		s = list(map(int, list(input())))
		ans = [None] * N
		zeroend = []
		oneend = []
		zero_len = 0
		one_len = 0
		val = 0
		for i in range(N):
			if s[i] == 0:
				if one_len == 0:
					val += 1
					ans[i] = val
					zeroend.append(val)
					zero_len += 1
				else:
					itr = oneend.pop()
					ans[i] = itr
					one_len -= 1
					zeroend.append(itr)
					zero_len += 1
			elif zero_len == 0:
				val += 1
				ans[i] = val
				oneend.append(val)
				one_len += 1
			else:
				itr = zeroend.pop()
				ans[i] = itr
				zero_len -= 1
				oneend.append(itr)
				one_len += 1
		print(val)
		print(*ans)
main()


def inp():
	return int(input())

def insr():
	s = input()
	return s

def inlt():
	return list(map(int, input().split()))

def solve(l):
	s1 = []
	s0 = []
	last = 0
	ans = []
	for i in range(len(l)):
		if l[i] == '0':
			if len(s1) == 0:
				last += 1
				s1.append(last)
			ans.append(s1[-1])
			s0.append(s1.pop())
		if l[i] == '1':
			if len(s0) == 0:
				last += 1
				s0.append(last)
			ans.append(s0[-1])
			s1.append(s0.pop())
	return (last, ans)
	return best
r = inp()
for i in range(r):
	a = inp()
	l2 = insr()
	(last, ans) = solve(l2)
	print(last)
	print(' '.join([str(i) for i in ans]))


import sys
import os
from math import sqrt, log, log2, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007
iinp = lambda : int(sys.stdin.readline())
inp = lambda : sys.stdin.readline().strip()
strl = lambda : list(inp().strip().split(' '))
intl = lambda : list(map(int, inp().split(' ')))
mint = lambda : map(int, inp().split())
flol = lambda : list(map(float, inp().split(' ')))
flush = lambda : stdout.flush()

def permute(nums):

	def fun(arr, nums, cur, v):
		if len(cur) == len(nums):
			arr.append(cur.copy())
		i = 0
		while i < len(nums):
			if v[i]:
				i += 1
				continue
			else:
				cur.append(nums[i])
				v[i] = 1
				fun(arr, nums, cur, v)
				cur.pop()
				v[i] = 0
				i += 1
		return arr
	res = []
	nums.sort()
	v = [0] * len(nums)
	return fun(res, nums, [], v)

def subsets(res, index, arr, cur):
	res.append(cur.copy())
	for i in range(index, len(arr)):
		cur.append(arr[i])
		subsets(res, i + 1, arr, cur)
		cur.pop()
	return res

def sieve(N):
	root = int(sqrt(N))
	primes = [1] * (N + 1)
	(primes[0], primes[1]) = (0, 0)
	for i in range(2, root + 1):
		if primes[i]:
			for j in range(i * i, N + 1, i):
				primes[j] = 0
	return primes

def bs(arr, l, r, x):
	if x < arr[0] or x > arr[len(arr) - 1]:
		return -1
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	p = int(sqrt(n))
	for i in range(5, p + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def solve():
	z = 0
	o = 0
	ans = []
	count = 0
	n = iinp()
	s = inp()
	for i in range(n):
		if s[i] == '0':
			if o > 0:
				ans.append(count - z)
				o -= 1
				z += 1
			else:
				count += 1
				ans.append(count)
				z += 1
		elif z > 0:
			ans.append(o + 1)
			z -= 1
			o += 1
		else:
			count += 1
			ans.append(count)
			o += 1
	print(count)
	print(*ans)
for _ in range(iinp()):
	solve()


from collections import defaultdict, deque

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input()))
		d = dict()
		d[0] = deque([])
		d[1] = deque([])
		s = set()
		l = [-1] * n
		j = 0
		for i in range(n):
			if len(d[a[i]]) == 0:
				j += 1
				l[i] = j
				d[1 - a[i]].append(i)
			else:
				x = d[a[i]].popleft()
				l[i] = l[x]
				d[1 - a[i]].append(i)
		print(max(l))
		print(*l)
main()


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	s = inp()
	zeroes = []
	ones = []
	groups = [0] * n
	g = 2
	flag = False
	if s[0] == '0':
		ones.append(1)
	else:
		zeroes.append(1)
	groups[0] = 1
	for i in range(1, n):
		if s[i] == '0':
			if zeroes:
				groups[i] = zeroes[len(zeroes) - 1]
				ones.append(zeroes.pop())
			else:
				flag = True
		elif ones:
			groups[i] = ones[len(ones) - 1]
			zeroes.append(ones.pop())
		else:
			flag = True
		if flag:
			groups[i] = g
			if s[i] == '0':
				ones.append(g)
			else:
				zeroes.append(g)
			g += 1
			flag = False
	print(g - 1)
	print(*groups)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)

def toord(c):
	return ord(c) - ord('a')

def lcm(a, b):
	return a * b // lcm(a, b)
mod = 998244353
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		n = N()
		s = list(input())
		res = []
		for i in range(n):
			now = s[i]
			if res and now != res[-1][-1]:
				res[-1].append(now)
			else:
				res.append([])
				res[-1].append(now)
		zero = []
		one = []
		tag = 1
		ret = []
		for i in range(len(res)):
			now = res[i][0]
			if now == '0':
				if one:
					pnum = one.pop()
					ret.extend([pnum] * len(res[i]))
				else:
					ret.extend([tag] * len(res[i]))
					tag += 1
			elif zero:
				pnum = zero.pop()
				ret.extend([pnum] * len(res[i]))
			else:
				ret.extend([tag] * len(res[i]))
				tag += 1
			lst = res[i][-1]
			if lst == '0':
				zero.append(ret[-1])
			else:
				one.append(ret[-1])
		print(max(ret))
		print(*ret)
main()


def calc(s, n):
	k = 0
	r = []
	zeros = []
	ones = []
	for a in s:
		if a == '0':
			src = ones
			dst = zeros
		else:
			src = zeros
			dst = ones
		if src:
			x = src.pop()
		else:
			k += 1
			x = str(k)
		r.append(x)
		dst.append(x)
	return (k, ' '.join(r))
T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	assert len(s) == n
	(k, r) = calc(s, n)
	print(k)
	print(r)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	k = 0
	out = []
	last_chars = [[], []]
	for i in range(n):
		c = s[i]
		oppc = '1' if c == '0' else '0'
		if len(last_chars[int(oppc)]) > 0:
			a = last_chars[int(oppc)].pop()
			last_chars[int(c)].append(a)
			out.append(str(a))
		else:
			k += 1
			last_chars[int(c)].append(k)
			out.append(str(k))
	print(k)
	print(' '.join(out))


from collections import defaultdict
for t in range(int(input())):
	n = int(input())
	s = str(input())
	i = 0
	m = []
	l = [[], []]
	d = defaultdict(list)
	while i < n:
		r = int(s[i])
		if len(l[1 - r]) == 0:
			p = len(l[r])
			d[p + 1].append(r)
			m.append(p + 1)
			l[r].append(p + 1)
			i += 1
		else:
			k = l[1 - r].pop()
			d[k].append(r)
			l[r].append(k)
			m.append(k)
			i += 1
	print(len(d.keys()))
	print(*m)


import sys
input = sys.stdin.readline
inf = int(10000000000.0)
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().strip()))
	(o, z) = ([], [])
	ans = [0] * n
	for i in range(n):
		v = len(z) + len(o)
		if a[i] == 1:
			if z:
				v = z.pop()
				o.append(v)
			else:
				o.append(v)
		elif o:
			v = o.pop()
			z.append(v)
		else:
			z.append(v)
		ans[i] = v + 1
	print(len(z) + len(o))
	print(*ans)


tests = int(input())
for t in range(tests):
	n = int(input())
	arr = list(map(int, input()))
	arr_res = [None for _ in range(n)]
	curr = 1
	check = True
	curr_item = None
	prev_start_idx = -1
	one_group = []
	zero_group = []
	for (idx, item) in enumerate(arr):
		if item == 0:
			if len(one_group) == 0:
				zero_group.append(curr)
				arr_res[idx] = curr
				curr += 1
			else:
				one_member = one_group.pop(-1)
				arr_res[idx] = one_member
				zero_group.append(one_member)
		elif item == 1:
			if len(zero_group) == 0:
				one_group.append(curr)
				arr_res[idx] = curr
				curr += 1
			else:
				zero_member = zero_group.pop(-1)
				arr_res[idx] = zero_member
				one_group.append(zero_member)
	print(curr - 1)
	print(' '.join(list(map(str, arr_res))))


import os, sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	for _ in range(int(input())):
		n = int(input())
		s = input().strip()
		(zero, one, ans, val) = (set(), set(), [], 0)
		for i in s:
			if i == '1':
				if len(one):
					x = one.pop()
					zero.add(x)
					ans.append(x)
				else:
					val += 1
					zero.add(val)
					ans.append(val)
			elif len(zero):
				x = zero.pop()
				one.add(x)
				ans.append(x)
			else:
				val += 1
				one.add(val)
				ans.append(val)
		print(len(zero) + len(one))
		print(' '.join(map(str, ans)))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	n = val()
	l = li3()
	d = defaultdict(list)
	ans = {}
	curr = 1
	for i in range(n):
		if len(d[1 - l[i]]):
			d[l[i]].append(d[1 - l[i]].pop())
			ans[i] = d[l[i]][-1]
		else:
			d[l[i]].append(curr)
			ans[i] = curr
			curr += 1
	print(curr - 1)
	for i in range(n):
		print(ans[i], end=' ')
	print()


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	stack1 = []
	stack0 = []
	ans = [0] * n
	for i in range(n):
		newPos = len(stack1) + len(stack0)
		if s[i] == '0':
			if stack1:
				newPos = stack1[-1]
				stack1.pop()
				stack0.append(newPos)
			else:
				stack0.append(newPos)
		elif stack0:
			newPos = stack0[-1]
			stack0.pop()
			stack1.append(newPos)
		else:
			stack1.append(newPos)
		ans[i] = newPos
	print(len(stack1) + len(stack0))
	for i in range(n):
		print(ans[i] + 1, end=' ')
	print()


import sys

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1000000000.0) + 7
for _ in range(iinput()):
	n = iinput()
	s = input()
	ans = []
	prev = {'0': 0, '1': 0}
	indexes = {'0': [], '1': []}
	res = [0 for _ in range(n)]
	l = len(ans)
	for i in range(n):
		if s[i] == '0':
			if prev['1'] > 0:
				prev['1'] -= 1
				ind = indexes['1'].pop(0)
				res[i] = ind + 1
				indexes['0'].append(ind)
			else:
				indexes['0'].append(l)
				l += 1
				res[i] = l
			prev['0'] += 1
		else:
			if prev['0'] > 0:
				prev['0'] -= 1
				ind = indexes['0'].pop(0)
				res[i] = ind + 1
				indexes['1'].append(ind)
			else:
				indexes['1'].append(l)
				l += 1
				res[i] = l
			prev['1'] += 1
	print(l)
	print(*res)


def solv():
	x = int(input())
	s = list(map(int, input()))
	stczr = []
	stcon = []
	dic = {}
	on = -1
	zr = -1
	if s[0] == 1:
		stcon.append(1)
		dic[1] = [1]
	else:
		stczr.append(1)
		dic[1] = [1]
	ind = 2
	for n in range(1, x):
		if s[n]:
			if len(stczr) != 0:
				v = stczr[-1]
				dic[v].append(n + 1)
				stczr.pop()
				stcon.append(v)
			else:
				dic[ind] = [n + 1]
				stcon.append(ind)
				ind += 1
		elif len(stcon) != 0:
			v = stcon[-1]
			dic[v].append(n + 1)
			stcon.pop()
			stczr.append(v)
		else:
			dic[ind] = [n + 1]
			stczr.append(ind)
			ind += 1
	ind = {}
	for n in dic:
		for k in dic[n]:
			ind[k] = n
	print(len(dic))
	for n in range(1, x + 1):
		print(ind[n], end=' ')
	print()
for _ in range(int(input())):
	solv()


for s in [*open(0)][2::2]:
	(k, r) = (0, [])
	for v in s[:-1]:
		k += v > '0'
		r += [k]
		k -= v < '1'
	k = min(r) - 1
	r = [a - k for a in r]
	print(max(r), *r)


def sol(a):
	b = []
	p = [[], []]
	c = 0
	for i in range(0, len(a)):
		if a[i] == '1':
			if len(p[0]):
				b[p[0][-1]].append(i)
				p[1].append(p[0][-1])
				p[0].pop()
			else:
				b.append([])
				b[-1].append(i)
				p[1].append(len(b) - 1)
		elif len(p[1]):
			b[p[1][-1]].append(i)
			p[0].append(p[1][-1])
			p[1].pop()
		else:
			b.append([])
			b[-1].append(i)
			p[0].append(len(b) - 1)
	return b
test = int(input())
for t in range(0, test):
	n = int(input())
	a = input()
	b = sol(a)
	c = []
	for i in range(0, len(a)):
		c.append(0)
	for i in range(0, len(b)):
		for e in b[i]:
			c[e] = i + 1
	print(max(c))
	for e in c:
		print(e, end=' ')
	print()

def decToBi(i, p):
	a = []
	for t in range(0, p):
		a.append(i % 2)
		i = i // 2
	a.reverse()
	return a

def check(c):
	for i in range(1, len(c)):
		if c[i - 1] == c[i]:
			return 0
	return 1

def main():
	p = 6
	for i in range(0, 2 ** p):
		a = decToBi(i, p)
		b = sol(a)
		c = []
		for i in range(0, p):
			c.append(0)
		for i in range(0, len(b)):
			for e in b[i]:
				c[e] = i + 1
		for i in range(0, max(c)):
			d = []
			for j in range(0, p):
				if c[j] == i + 1:
					d.append(a[j])
			if check(d) == 0:
				print(a)
				print(b)
				print(i + 1, d)
				print()


import os
import sys
from io import BytesIO, IOBase
import threading
from collections import defaultdict

def main():
	n = int(input())
	arr = [int(c) for c in input()]
	ans = [-1] * n
	s1 = []
	s0 = []
	p = 1
	for i in range(n):
		if arr[i] == 1:
			if len(s0) == 0:
				arr[i] = p
				s1.append(p)
				p += 1
			else:
				k = s0.pop()
				arr[i] = k
				s1.append(k)
		elif len(s1) == 0:
			arr[i] = p
			s0.append(p)
			p += 1
		else:
			k = s1.pop()
			arr[i] = k
			s0.append(k)
	print(max(arr))
	print(*arr)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(int(input())):
	main()


def solve4(s):
	n = len(s)
	ans = []
	ans.append(1)
	(odd_stack, even_stack) = ([], [])
	if s[0] == '1':
		odd_stack = [['1', 1]]
	else:
		even_stack = [['0', 1]]
	(odd, even) = (None, None)
	index = 1
	for i in range(1, n):
		if s[i] == '1':
			if even_stack:
				even = even_stack[-1]
				ans.append(even[1])
				even_stack.pop()
				odd_stack.append([even[0] + '1', even[1]])
			else:
				index += 1
				ans.append(index)
				odd_stack.append(['1', index])
		elif odd_stack:
			odd = odd_stack[-1]
			ans.append(odd[1])
			odd_stack.pop()
			even_stack.append([odd[0] + '0', odd[1]])
		else:
			index += 1
			ans.append(index)
			even_stack.append(['0', index])
	k = max(ans)
	print(k)
	for i in ans:
		print(i, ' ', end='')
	print()
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	solve4(s)


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = stdin.readline().strip()
	l = []
	zeros = []
	ones = []
	if s[0] == '1':
		ones = [1]
	else:
		zeros = [1]
	count = 1
	for i in s:
		if i == '0':
			if len(zeros):
				l.append(zeros.pop(-1))
				ones.append(l[-1])
			else:
				count += 1
				l.append(count)
				ones.append(count)
		elif len(ones):
			l.append(ones.pop(-1))
			zeros.append(l[-1])
		else:
			count += 1
			l.append(count)
			zeros.append(count)
	stdout.write(f'{count}\n' + ' '.join(map(str, l)) + '\n')


t = int(input())
for case in range(t):
	n = int(input())
	s = input().strip()
	a = [[], []]
	ret = ''
	i = 1
	a0 = 0
	a1 = 0
	for x in s:
		if x == '1' and a0:
			tmp = a[0][-1]
			ret += tmp + ' '
			a[0].pop(-1)
			a[1].append(tmp)
			a0 -= 1
			a1 += 1
		elif x == '1' and (not a0):
			a[1].append(str(i))
			a1 += 1
			ret += str(i) + ' '
			i += 1
		elif a1:
			tmp = a[1][-1]
			ret += tmp + ' '
			a[1].pop(-1)
			a1 -= 1
			a[0].append(tmp)
			a0 += 1
		else:
			a[0].append(str(i))
			a0 += 1
			ret += str(i) + ' '
			i += 1
	print(i - 1)
	print(ret)


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	a = []
	b = []
	idx = 0
	ans = [0] * n
	for i in range(n):
		if s[i] == '0':
			if len(b) > 0:
				temp = b.pop()
				ans[i] = temp
				a.append(temp)
			else:
				idx += 1
				ans[i] = idx
				a.append(idx)
		elif len(a) > 0:
			temp = a.pop()
			ans[i] = temp
			b.append(temp)
		else:
			idx += 1
			ans[i] = idx
			b.append(idx)
	k = len(set(ans))
	print(k)
	print(*ans)


T = int(input())
for i in range(T):
	length = int(input())
	s = input()
	(zero, one) = ([], [])
	arr = [0] * length
	for (i, char) in enumerate(s):
		if char == '0':
			if not one:
				new_pos = len(zero) + 1
				zero.append(new_pos)
			else:
				new_pos = one.pop()
				zero.append(new_pos)
		elif not zero:
			new_pos = len(one) + 1
			one.append(new_pos)
		else:
			new_pos = zero.pop()
			one.append(new_pos)
		arr[i] = new_pos
	print(len(one) + len(zero))
	print(' '.join((str(item) for item in arr)))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input().rstrip()
	s = [s[-i - 1] for i in range(n)]
	ans = []
	zero = []
	one = []
	res = [-1] * n
	pos = 0
	while s:
		b = s.pop()
		if b == '0':
			if not one:
				new = 1
				ans.append(new)
				res[pos] = len(ans)
				zero.append(len(ans) - 1)
			else:
				id = one.pop()
				ans[id] += 1
				res[pos] = id + 1
				zero.append(id)
		elif not zero:
			new = 1
			ans.append(new)
			res[pos] = len(ans)
			one.append(len(ans) - 1)
		else:
			id = zero.pop()
			ans[id] += 1
			res[pos] = id + 1
			one.append(id)
		pos += 1
	print(len(ans))
	print(*res)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('../output.txt', 'w')
except:
	pass

class solve:

	def __init__(self):
		self.d = {}
		self.ptr = 0
		self.one = []
		self.zero = []
		self.ans = {}

	def x(self, idx):
		if s[idx] == '1':
			if not self.zero:
				self.one.append(self.ptr + 1)
				self.ptr += 1
				temp = self.d.get(self.ptr, [])
				temp.append(idx)
				self.d[self.ptr] = temp
				self.ans[idx] = self.ptr
			else:
				a = self.zero[0]
				del self.zero[0]
				self.one.append(a)
				self.d[a].append(idx)
				self.ans[idx] = a
		elif s[idx] == '0':
			if not self.one:
				self.zero.append(self.ptr + 1)
				self.ptr += 1
				temp = self.d.get(self.ptr, [])
				temp.append(idx)
				self.d[self.ptr] = temp
				self.ans[idx] = self.ptr
			else:
				a = self.one[0]
				del self.one[0]
				self.zero.append(a)
				self.d[a].append(idx)
				self.ans[idx] = a

	def printsol(self):
		print(self.ptr)
		for i in range(n):
			print(self.ans[i], end=' ')
		print()
for _ in range(L()[0]):
	n = L()[0]
	s = input()
	obj = solve()
	for i in range(n):
		obj.x(i)
	obj.printsol()


from sys import stdin

def main():
	(_, res) = (input(), stdin.read().splitlines())
	for i in range(1, len(res), 2):
		(row, z, o, idx) = (list(map(int, res[i])), [], [], 0)
		d = ((z, o.append), (o, z.append))
		for (j, ch) in enumerate(row):
			(src, push) = d[ch]
			if src:
				k = src.pop()
			else:
				idx += 1
				k = idx
			push(k)
			row[j] = k
		(res[i - 1], res[i]) = (str(idx), ' '.join(map(str, row)))
	print('\n'.join(res))
main()


def solve(N, A):
	used = [''] * N
	curr_ones = []
	curr_zeroes = []
	counter = 1
	for i in range(N - 1, -1, -1):
		value = A[i]
		if value == '1':
			if curr_zeroes:
				idx = curr_zeroes.pop()
				used[i] = used[idx]
				curr_ones.append(i)
			else:
				used[i] = str(counter)
				curr_ones.append(i)
				counter += 1
		elif curr_ones:
			idx = curr_ones.pop()
			used[i] = used[idx]
			curr_zeroes.append(i)
		else:
			used[i] = str(counter)
			curr_zeroes.append(i)
			counter += 1
	return (used, counter)

def main():
	T = int(input())
	for _ in range(T):
		N = int(input())
		A = input().rstrip()
		(ans, k) = solve(N, A)
		print(k - 1)
		print(' '.join(ans))
main()


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(input())
	brr = []
	crr = []
	drr = []
	for i in range(1000):
		drr.append(i + 1)
	for i in range(n):
		if arr[i] == '1':
			if len(brr) == 0:
				crr.append([i])
			else:
				crr.append(brr.pop())
				crr[-1].append(i)
		elif len(crr) == 0:
			brr.append([i])
		else:
			brr.append(crr.pop())
			brr[-1].append(i)
	answer = [0] * n
	for i in range(len(crr)):
		for j in crr[i]:
			answer[j] = i + 1
	for i in range(len(brr)):
		for j in brr[i]:
			answer[j] = i + 1 + len(crr)
	print(len(crr) + len(brr))
	print(*answer)


from collections import deque
t = int(input())
for _ in range(0, t):
	n = int(input())
	s = input()
	(zeroes, ones) = (deque([]), deque([]))
	total_subs = 0
	ans = []
	for i in range(0, n):
		if s[i] == '0':
			if len(ones) == 0:
				total_subs += 1
				ans.append(total_subs)
				zeroes.append(total_subs)
			else:
				k = ones.pop()
				ans.append(k)
				zeroes.append(k)
		elif len(zeroes) == 0:
			total_subs += 1
			ans.append(total_subs)
			ones.append(total_subs)
		else:
			k = zeroes.pop()
			ans.append(k)
			ones.append(k)
	print(total_subs)
	print(*ans)


t = int(input())
for q in range(t):
	n = int(input())
	s = input()
	az = []
	ao = []
	cc = 1
	ans = []
	j = 0
	for i in s:
		if i == '0':
			l = len(ao)
			if l == 0:
				az.append(cc)
				ans.append(cc)
				cc += 1
			else:
				p = ao.pop()
				az.append(p)
				ans.append(p)
		else:
			l = len(az)
			if l == 0:
				ao.append(cc)
				ans.append(cc)
				cc += 1
			else:
				p = az.pop()
				ao.append(p)
				ans.append(p)
	print(cc - 1)
	print(*ans, end=' ')
	print()


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		s = S()
		c = collections.defaultdict(list)
		t = 0
		o = []
		z = []
		r = []
		for (i, a) in enumerate(s, 1):
			if a == '1':
				if z:
					j = z[-1]
					del z[-1]
				else:
					t += 1
					j = t
				r.append(j)
				o.append(j)
			else:
				if o:
					j = o[-1]
					del o[-1]
				else:
					t += 1
					j = t
				r.append(j)
				z.append(j)
		rr.append(t)
		rr.append(JA(r, ' '))
	return JA(rr, '\n')
print(main())


import sys
input = sys.stdin.readline

def name(arr):
	from collections import deque
	o = deque([])
	z = deque([])
	ans = []
	count = 0
	for i in range(len(arr[:-1])):
		if arr[i] == '0':
			if len(o) > 0:
				popped = o.popleft()
				z.append(popped)
				ans.append(str(popped))
			else:
				count += 1
				z.append(count)
				ans.append(str(count))
		elif arr[i] == '1':
			if len(z) > 0:
				popped = z.popleft()
				o.append(popped)
				ans.append(str(popped))
			else:
				count += 1
				o.append(count)
				ans.append(str(count))
	print(count)
	print(' '.join(ans))

def solution():
	n = int(input())
	arr = list(input())
	name(arr)
t = int(input())
for i in range(0, t):
	solution()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	n = len(s)
	s1 = 0
	s0 = 0
	ans = 1
	ansli = [1]
	arr1 = []
	arr0 = []
	if s[0] == '1':
		s1 = 1
		arr1.append(0)
	else:
		s0 = 1
		arr0.append(0)
	for i in range(1, n):
		if s[i] == '1':
			if len(arr0) > 0:
				ansli.append(ansli[arr0.pop(-1)])
				arr1.append(i)
			else:
				ans += 1
				ansli.append(ans)
				arr1.append(i)
		elif len(arr1) > 0:
			ansli.append(ansli[arr1.pop(-1)])
			arr0.append(i)
		else:
			ans += 1
			ansli.append(ans)
			arr0.append(i)
	print(ans)
	print(*ansli)


for i in range(int(input())):
	v = [''] * int(input())
	(a, q, ans) = (input(), [[], []], 0)
	for j in range(len(a)):
		i = int(a[j])
		if q[i % 2]:
			v[j] = q[i % 2].pop()
			q[1 - i % 2].append(v[j])
		else:
			ans += 1
			v[j] = ans
			q[1 - i % 2].append(ans)
	print(ans)
	print(*v)


import os
import sys
from io import BytesIO, IOBase
import math
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	s = input()
	z = []
	o = []
	t = 0
	ans = [0] * n
	for i in range(n):
		if s[i] == '0':
			if o == []:
				t += 1
				z.append(t)
				ans[i] = t
			else:
				var = o.pop()
				z.append(var)
				ans[i] = var
		elif z == []:
			t += 1
			o.append(t)
			ans[i] = t
		else:
			w = z.pop()
			o.append(w)
			ans[i] = w
	print(t)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = []
	pos0 = []
	pos1 = []
	pre_pos = 0
	for i in range(len(s)):
		pre_pos = len(pos1) + len(pos0)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(pre_pos)
			else:
				pre_pos = pos1.pop()
				pos0.append(pre_pos)
		elif len(pos0) == 0:
			pos1.append(pre_pos)
		else:
			pre_pos = pos0.pop()
			pos1.append(pre_pos)
		ans.append(pre_pos + 1)
	print(len(pos1) + len(pos0))
	print(' '.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, list(input())))
	ca = [1] * n
	end = [[], []]
	m = 1
	for i in range(1, n):
		if A[i] == A[i - 1]:
			end[A[i - 1]].append(i - 1)
			if end[(A[i] + 1) % 2]:
				ca[i] = ca[end[(A[i] + 1) % 2].pop()]
			else:
				m += 1
				ca[i] = m
		else:
			ca[i] = ca[i - 1]
	print(m)
	print(*ca)


from functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	n = int(input())
	s = input()
	z = []
	o = []
	ans = [0] * n
	temp = 0
	for i in range(n):
		if s[i] == '0':
			if len(z) == 0:
				if len(o) == 0:
					ans[i] = 1
					o.append(1)
				else:
					ans[i] = len(o) + 1
					o.append(len(o) + 1)
			else:
				ans[i] = z[-1]
				temp = z.pop()
				o.append(temp)
		elif len(o) == 0:
			if len(z) == 0:
				ans[i] = 1
				z.append(1)
			else:
				ans[i] = len(z) + 1
				z.append(len(z) + 1)
		else:
			ans[i] = o[-1]
			temp = o.pop()
			z.append(temp)
	print(max(ans))
	print(*ans)


mod = 10 ** 9 + 7

def solve():
	n = int(input())
	s = input()
	s0 = []
	s1 = []
	vec = []
	sm = 0
	for i in range(n):
		if s[i] == '1':
			if len(s0) < 1:
				sm += 1
				s1.append(sm)
				vec.append(sm)
			else:
				vec.append(s0[len(s0) - 1])
				s1.append(s0[len(s0) - 1])
				s0.pop()
		elif len(s1) < 1:
			sm += 1
			s0.append(sm)
			vec.append(sm)
		else:
			vec.append(s1[len(s1) - 1])
			s0.append(s1[len(s1) - 1])
			s1.pop()
	print(sm)
	print(*vec, sep=' ')
t = 1
t = int(input())
for _ in range(t):
	solve()


for _ in range(int(input())):
	n = int(input())
	s = input()
	p0 = []
	p1 = []
	seq = [0] * n
	last = 0
	for i in range(n):
		if s[i] == '0':
			if p1:
				q = p1.pop()
				p0.append(q)
			else:
				last += 1
				q = last
				p0.append(q)
		elif s[i] == '1':
			if p0:
				q = p0.pop()
				p1.append(q)
			else:
				last += 1
				q = last
				p1.append(q)
		seq[i] = q
	print(len(p0) + len(p1))
	print(*seq)


import sys
from functools import lru_cache
from collections import defaultdict

def solve(s):
	sub_map = [0 for _ in range(len(s))]
	sub_map[len(s) - 1] = 1
	zero_seqs = [1] if s[-1] == '0' else []
	one_seqs = [1] if s[-1] == '1' else []
	largest = 1
	for i in range(len(s) - 2, -1, -1):
		curr = s[i]
		if curr == '1' and zero_seqs:
			seq_num = zero_seqs.pop()
			sub_map[i] = seq_num
			one_seqs.append(seq_num)
		elif curr == '0' and one_seqs:
			seq_num = one_seqs.pop()
			sub_map[i] = seq_num
			zero_seqs.append(seq_num)
		elif curr == '1':
			largest += 1
			sub_map[i] = largest
			one_seqs.append(largest)
		else:
			largest += 1
			sub_map[i] = largest
			zero_seqs.append(largest)
	return (len(zero_seqs) + len(one_seqs), sub_map)

def main(mat):
	for s in mat:
		(rest, sub_map) = solve(s)
		print(rest)
		print(' '.join((str(d) for d in sub_map)))
mat = []
for (e, line) in enumerate(sys.stdin.readlines()):
	if e == 0:
		continue
	elif e % 2 == 0:
		mat.append(line.strip())
main(mat)


def solution():
	n = int(input())
	s = list(input())
	zero = []
	one = []
	ans = 0
	grp = 0
	grparr = []
	for i in range(n):
		if s[i] == '0':
			if one != []:
				zero.append(one[-1])
				one.pop()
				grparr.append(zero[-1])
			else:
				grp += 1
				ans += 1
				zero.append(grp)
				grparr.append(grp)
		elif zero != []:
			one.append(zero[-1])
			grparr.append(one[-1])
			zero.pop()
		else:
			ans += 1
			grp += 1
			one.append(grp)
			grparr.append(grp)
	print(ans)
	print(*grparr)
t = int(input())
for _ in range(t):
	solution()


from math import *
from collections import *
from random import *
from decimal import Decimal
from bisect import *
import sys
input = sys.stdin.readline

def lis():
	return list(map(int, input().split()))

def ma():
	return map(int, input().split())

def inp():
	return int(input())

def st():
	return input().rstrip('\n')
t = inp()
while t:
	t -= 1
	n = inp()
	a = st()
	one = deque([])
	zero = deque([])
	cur = 1
	r = []
	for i in a:
		if i == '1':
			if len(zero) == 0:
				one.append(cur)
				r.append(cur)
				cur += 1
			else:
				x = zero.pop()
				r.append(x)
				one.appendleft(x)
		elif len(one) == 0:
			zero.append(cur)
			r.append(cur)
			cur += 1
		else:
			x = one.pop()
			r.append(x)
			zero.appendleft(x)
	print(max(r))
	print(*r)


t = int(input())
S = []
for i in range(t):
	n = int(input())
	s = str(input())
	S.append(s)
for s in S:
	ans = [1]
	count = 1
	which = None
	maxcount = 1
	d = {}
	set0 = []
	set1 = []
	count = 2
	if s[0] == '0':
		set0.append(1)
	else:
		set1.append(1)
	for c in s[1:]:
		if c == '1':
			if len(set0) > 0:
				p = set0.pop()
			else:
				p = count
				count += 1
			set1.append(p)
		else:
			if len(set1) > 0:
				p = set1.pop()
			else:
				p = count
				count += 1
			set0.append(p)
		ans.append(p)
	print(count - 1)
	print(' '.join(map(str, ans)))


t = int(input())
for ii in range(t):
	n = int(input())
	s = input()
	ans = [1]
	end1 = []
	end0 = []
	e1m = -1
	e0m = -1
	if s[0] == '1':
		end1.append(1)
		e1m = 1
	else:
		end0.append(1)
		e0m = 1
	for i in range(1, n):
		if s[i] == '0':
			if len(end1) > 0:
				ans.append(end1[-1])
				end0.append(end1.pop(-1))
				if end0[-1] > e0m:
					e0m = end0[-1]
			else:
				ans.append(e0m + 1)
				end0.append(e0m + 1)
				e0m += 1
		elif len(end0) > 0:
			ans.append(end0[-1])
			end1.append(end0.pop(-1))
			if end1[-1] > e1m:
				e1m = end1[-1]
		else:
			ans.append(e1m + 1)
			end1.append(e1m + 1)
			e1m += 1
	print(max(ans))
	print(*ans)


from collections import deque
for item in [0] * int(input()):
	n = int(input())
	s = input()
	q0 = deque()
	q1 = deque()
	a = []
	num = 1
	for i in range(n):
		if s[i] == '0':
			if len(q0) == 0:
				a.append(num)
				q1.append(num)
				num += 1
			else:
				q1.append(q0[len(q0) - 1])
				a.append(q0.pop())
		elif len(q1) == 0:
			a.append(num)
			q0.append(num)
			num += 1
		else:
			q0.append(q1[len(q1) - 1])
			a.append(q1.pop())
	print(max(a))
	print(' '.join((str(ele) for ele in a)))


from os import path
import sys
from heapq import heappush, heappop, heapify
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def b(i):
	return ord(i) - ord('a')
file = 1

def solve():
	for _ in range(ii()):
		n = ii()
		s = si()
		ans = 0
		(z, o, z_o, o_z) = ([], [], [], [])
		x = [0] * n
		c = 0
		for i in range(n):
			if s[i] == '0':
				if len(o):
					x[i] = o[-1]
					o.pop()
					o_z.append(x[i])
				elif len(z_o):
					x[i] = z_o[-1]
					z_o.pop()
					z.append(x[i])
				else:
					c += 1
					z.append(c)
					x[i] = c
			elif len(z):
				x[i] = z[-1]
				z.pop()
				z_o.append(x[i])
			elif len(o_z):
				x[i] = o_z[-1]
				o_z.pop()
				o.append(x[i])
			else:
				c += 1
				o.append(c)
				x[i] = c
		print(len(set(x)))
		print(*x)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


(z, zz, dgraphs) = (input, lambda : list(map(int, z().split())), {})
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
for _ in range(int(input())):
	n = int(input())
	l = z()
	A = list(map(int, list(l)))
	ca = [1] * n
	end = [[], []]
	m = 1
	for i in range(1, n):
		if A[i] == A[i - 1]:
			end[A[i - 1]].append(i - 1)
			if end[(A[i] + 1) % 2]:
				ca[i] = ca[end[(A[i] + 1) % 2].pop()]
			else:
				m += 1
				ca[i] = m
		else:
			ca[i] = ca[i - 1]
	print(m)
	print(*ca)


for t in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input()[:n]]
	(ans, temp, exp) = ([], [[], []], 0)
	for i in arr:
		x = 1 - i
		if len(temp[x]) > 0:
			p = temp[x].pop()
			temp[i].append(p)
		else:
			exp += 1
			temp[i].append(exp)
			p = exp
		ans.append(p)
	print(max(ans))
	print(*ans)


for t in range(int(input())):
	n = int(input())
	s = input()
	(sz, so, res) = ([], [], [0 for x in range(n)])
	count = 0
	for i in range(n):
		if s[i] == '0':
			if not so:
				count += 1
				res[i] = count
				sz.append(count)
			else:
				c = so.pop()
				res[i] = c
				sz.append(c)
		elif not sz:
			count += 1
			res[i] = count
			so.append(count)
		else:
			c = sz.pop()
			res[i] = c
			so.append(c)
	print(count)
	print(*res)


for _ in range(int(input())):
	n = int(input())
	s = list(input())
	tmp = [1] * n
	x = s[0]
	c = 1
	for i in range(n):
		if s[i] == x:
			tmp[i] = c
			c += 1
		else:
			tmp[i] = c - 1
			c -= 1
	k = min(tmp)
	if k <= 0:
		for i in range(n):
			tmp[i] = tmp[i] + 1 + abs(k)
	ans = max(tmp)
	print(max(tmp))
	print(*tmp)


from sys import stdin, stdout
from collections import defaultdict as dd
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(input())
	a.pop()
	z = []
	e = []
	for i in range(n):
		if a[i] == '1':
			if len(z) == 0:
				e.append([i])
			else:
				e.append(z.pop())
				e[-1].append(i)
		elif len(e) == 0:
			z.append([i])
		else:
			z.append(e.pop())
			z[-1].append(i)
	ans = [0] * n
	for i in range(len(e)):
		for j in e[i]:
			ans[j] = i + 1
	for i in range(len(z)):
		for j in z[i]:
			ans[j] = i + 1 + len(e)
	print(len(e) + len(z))
	print(*ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	length = int(stdin.readline())
	string = stdin.readline().strip()
	ans = [0] * length
	count = 1
	curone = []
	curzero = []
	for a in range(length):
		i = string[a]
		if i == '0':
			if len(curone) == 0:
				curzero.append(count)
				ans[a] = count
				count += 1
			else:
				ans[a] = curone.pop()
				curzero.append(ans[a])
		elif len(curzero) == 0:
			curone.append(count)
			ans[a] = count
			count += 1
		else:
			ans[a] = curzero.pop()
			curone.append(ans[a])
	print(count - 1)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	res = []
	ones = []
	zeros = []
	ans = 0
	for c in s:
		if c == '0':
			if len(ones) == 0:
				ans += 1
				zeros.append(ans)
				res.append(ans)
			else:
				x = ones[len(ones) - 1]
				ones.pop()
				zeros.append(x)
				res.append(x)
		elif len(zeros) == 0:
			ans += 1
			ones.append(ans)
			res.append(ans)
		else:
			x = zeros[len(zeros) - 1]
			zeros.pop()
			ones.append(x)
			res.append(x)
	print(ans)
	for k in res:
		print(k, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	one = []
	zero = []
	ans = []
	z = 0
	o = 0
	total = 0
	for i in range(n):
		if a[i] == '1':
			if z == 0:
				one.append(total + 1)
				ans.append(total + 1)
				total += 1
				o += 1
			else:
				k = zero.pop()
				ans.append(k)
				one.append(k)
				z -= 1
				o += 1
		elif o == 0:
			ans.append(total + 1)
			zero.append(total + 1)
			total += 1
			z += 1
		else:
			k = one.pop()
			ans.append(k)
			zero.append(k)
			o -= 1
			z += 1
	print(max(ans))
	print(*ans)


import sys
import math, bisect
from collections import defaultdict
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, OrderedDict

def neo():
	return map(int, input().split())

def Neo():
	return list(map(int, input().split()))
for _ in range(int(input())):
	n = int(input())
	s = list(input())
	tmp = [1] * n
	x = s[0]
	c = 1
	for i in range(n):
		if s[i] == x:
			tmp[i] = c
			c += 1
		else:
			tmp[i] = c - 1
			c -= 1
	k = min(tmp)
	if k <= 0:
		for i in range(n):
			tmp[i] = tmp[i] + 1 + abs(k)
	ans = max(tmp)
	print(max(tmp))
	print(*tmp)


T = int(input())
for case in range(T):
	n = int(input())
	s = list(map(int, str(input())))
	ans = [0 for _ in range(n)]
	endBy = [[], []]
	max = 0
	for k in range(n):
		if endBy[1 - s[k]]:
			strnum = endBy[1 - s[k]].pop()
			ans[k] = strnum
			endBy[s[k]].append(strnum)
		else:
			max += 1
			endBy[s[k]].append(max)
			ans[k] = max
	print(max)
	print(' '.join(map(str, ans)))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	res = []
	pos0 = []
	pos1 = []
	newpos = 1
	for ch in s:
		if ch == '0':
			if pos1:
				snum = pos1.pop()
				curpos = snum
				pos0.append(snum)
			else:
				curpos = newpos
				pos0.append(newpos)
				newpos += 1
		elif pos0:
			snum = pos0.pop()
			curpos = snum
			pos1.append(snum)
		else:
			curpos = newpos
			pos1.append(newpos)
			newpos += 1
		res.append(curpos)
	print(newpos - 1)
	for p in res:
		print(p, end=' ')
	print()


t = int(input())
for tt in range(t):
	n = int(input())
	s = input()
	k = 1
	act_one = []
	act_zero = []
	belong = [0] * n
	for i in range(n):
		if s[i] == '0':
			if len(act_one) != 0:
				act_zero.append(act_one[-1])
				belong[i] = act_one[-1]
				del act_one[-1]
			else:
				belong[i] = k
				act_zero.append(k)
				k += 1
		if s[i] == '1':
			if len(act_zero) != 0:
				act_one.append(act_zero[-1])
				belong[i] = act_zero[-1]
				del act_zero[-1]
			else:
				belong[i] = k
				act_one.append(k)
				k += 1
	print(k - 1)
	for i in range(n):
		print(belong[i], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = [0] * n
	(pos_zero, pos_one) = ([], [])
	for i in range(n):
		new_pos = len(pos_zero) + len(pos_one)
		if s[i] == '0':
			if len(pos_one) == 0:
				pos_zero.append(new_pos)
			else:
				new_pos = pos_one.pop()
				pos_zero.append(new_pos)
		elif len(pos_zero) == 0:
			pos_one.append(new_pos)
		else:
			new_pos = pos_zero.pop()
			pos_one.append(new_pos)
		ans[i] = new_pos
	print(len(pos_one) + len(pos_zero))
	for i in range(n):
		print(ans[i] + 1, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = input()
	countr = 0
	segments = list()
	for ch in s:
		if ch == '1':
			countr += 1
		segments.append(countr)
		if ch == '0':
			countr -= 1
	num_of_segments = max(segments) - min(segments) + 1
	print(num_of_segments)
	min_segment_number = min(segments) - 1
	output = [x - min_segment_number for x in segments]
	print(*output)


for _ in range(int(input())):
	n = int(input())
	a = input()
	d = {0: [], 1: []}
	d[int(a[0])].append(0)
	curr = 1
	ans = [-1] * n
	ans[0] = 0
	for i in range(1, n):
		flag = 0
		if a[i] == '1':
			if not d[0]:
				d[1].append(curr)
				ans[i] = curr
				curr += 1
			else:
				k = d[0].pop()
				d[1].append(k)
				ans[i] = k
		elif a[i] == '0':
			if not d[1]:
				d[0].append(curr)
				ans[i] = curr
				curr += 1
			else:
				k = d[1].pop()
				d[0].append(k)
				ans[i] = k
	print(curr)
	for i in ans:
		print(i + 1, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	c = 0
	(s0, s1) = ([], [])
	o = []
	for ch in s:
		if ch == '0':
			if s0:
				i = s0.pop()
			else:
				c += 1
				i = c
			s1.append(i)
			o.append(str(i))
		else:
			if s1:
				i = s1.pop()
			else:
				c += 1
				i = c
			s0.append(i)
			o.append(str(i))
	print(c)
	print(' '.join(o))


t = int(input())
for _ in range(t):
	n = int(input())
	s = input().strip()
	one = []
	zero = []
	for (i, c) in enumerate(s):
		if c == '1':
			if zero:
				lst = zero.pop()
				lst.append(i)
				one.append(lst)
			else:
				one.append([i])
		elif one:
			lst = one.pop()
			lst.append(i)
			zero.append(lst)
		else:
			zero.append([i])
	res = one + zero
	print(len(res))
	I = [0] * n
	for i in range(len(res)):
		for j in res[i]:
			I[j] = i + 1
	print(*I)


for _ in range(int(input())):
	n = int(input())
	t = input()
	a = [1] * n
	z = []
	o = []
	g = 1
	for i in range(n):
		if t[i] == '0':
			if o:
				x = o.pop()
				a[i] = x
				z.append(x)
			else:
				a[i] = g
				z.append(g)
				g += 1
		elif z:
			x = z.pop()
			a[i] = x
			o.append(x)
		else:
			a[i] = g
			o.append(g)
			g += 1
	print(max(a))
	print(*a)


t = int(input())

def solve():
	n = int(input())
	s = input()
	ones = []
	zeros = []
	assign = [None] * n
	seq = 0
	for (i, x) in enumerate(s):
		if x == '1':
			if len(zeros):
				loc = zeros.pop()
				assign[i] = loc
				ones.append(loc)
			else:
				seq += 1
				assign[i] = seq
				ones.append(seq)
		elif len(ones):
			loc = ones.pop()
			assign[i] = loc
			zeros.append(loc)
		else:
			seq += 1
			zeros.append(seq)
			assign[i] = seq
	print(seq)
	print(*assign, sep=' ')
	return
while t:
	solve()
	t -= 1


import sys
input = sys.stdin.readline
T = int(input())

def update_min2(k, x):
	k += num_min - 1
	seg_min2[k] = x
	while k:
		k = (k - 1) // 2
		seg_min2[k] = min(seg_min2[k * 2 + 1], seg_min2[k * 2 + 2])

def query_min2(p, q):
	if q <= p:
		return ide_ele_min
	p += num_min - 1
	q += num_min - 2
	res = ide_ele_min
	while q - p > 1:
		if p & 1 == 0:
			res = min(res, seg_min2[p])
		if q & 1 == 1:
			res = min(res, seg_min2[q])
			q -= 1
		p = p // 2
		q = (q - 1) // 2
	if p == q:
		res = min(res, seg_min2[p])
	else:
		res = min(min(res, seg_min2[p]), seg_min2[q])
	return res

def update_min(k, x):
	k += num_min - 1
	seg_min[k] = x
	while k:
		k = (k - 1) // 2
		seg_min[k] = min(seg_min[k * 2 + 1], seg_min[k * 2 + 2])

def query_min(p, q):
	if q <= p:
		return ide_ele_min
	p += num_min - 1
	q += num_min - 2
	res = ide_ele_min
	while q - p > 1:
		if p & 1 == 0:
			res = min(res, seg_min[p])
		if q & 1 == 1:
			res = min(res, seg_min[q])
			q -= 1
		p = p // 2
		q = (q - 1) // 2
	if p == q:
		res = min(res, seg_min[p])
	else:
		res = min(min(res, seg_min[p]), seg_min[q])
	return res
for testcase in range(T):
	n = int(input())
	s = list(input())
	ide_ele_min = 10 ** 10
	num_min = 2 ** (n - 1).bit_length()
	seg_min = [ide_ele_min] * 2 * num_min
	seg_min2 = [ide_ele_min] * 2 * num_min
	a = [0] * n
	for i in range(n):
		if s[i] == '0':
			update_min(i, i)
		else:
			update_min2(i, i)
	k = 0
	for i in range(n):
		if a[i] != 0:
			continue
		k += 1
		a[i] = k
		idx = i
		if s[i] == '0':
			flag = True
		else:
			flag = False
		while True:
			if flag:
				p = query_min2(idx, n)
				if p == 10 ** 10:
					break
				idx = p
				flag = False
				a[idx] = k
				update_min2(idx, 10 ** 10)
			else:
				p = query_min(idx, n)
				if p == 10 ** 10:
					break
				idx = p
				flag = True
				a[idx] = k
				update_min(idx, 10 ** 10)
	print(k)
	print(*a)


for _ in ' ' * int(input()):
	n = int(input())
	s = input()
	ans = [-1] * n
	st0 = []
	st1 = []
	stcnt = 1
	for i in range(n):
		if s[i] == '0':
			if st1:
				ans[i] = st1[-1]
				st0.append(st1.pop())
			else:
				ans[i] = stcnt
				st0.append(stcnt)
				stcnt += 1
		elif st0:
			ans[i] = st0[-1]
			st1.append(st0.pop())
		else:
			ans[i] = stcnt
			st1.append(stcnt)
			stcnt += 1
	print(stcnt - 1)
	print(*ans)


t = int(input())
import heapq
for _ in range(t):
	n = int(input())
	s = input()
	k = 0
	a = []
	b = []
	heapq.heapify(a)
	heapq.heapify(b)
	l = []
	for i in s:
		if i == '0':
			try:
				x = heapq.heappop(b)
				l.append(x)
				heapq.heappush(a, x)
			except:
				k += 1
				heapq.heappush(a, k)
				l.append(k)
		else:
			try:
				x = heapq.heappop(a)
				l.append(x)
				heapq.heappush(b, x)
			except:
				k += 1
				heapq.heappush(b, k)
				l.append(k)
	print(k)
	print(*l)


from sys import setrecursionlimit
setrecursionlimit(10 ** 9)
import threading
threading.stack_size(67108864)

def solution():
	n = int(input())
	s = list(map(int, list(input())))
	answer = ['0'] * n
	cnt = 0
	seq = [[], []]
	for i in range(n):
		if len(seq[1 - s[i]]) == 0:
			cnt += 1
			seq[s[i]].append(cnt)
			answer[i] = str(cnt)
		else:
			seq_id = seq[1 - s[i]][-1]
			answer[i] = str(seq_id)
			seq[s[i]].append(seq_id)
			seq[1 - s[i]].pop()
	print(f'{cnt}')
	print(' '.join(answer))
t = int(input())
for _ in range(t):
	solution()


import sys
T = int(input())
for _ in range(T):
	N = int(input())
	S = list(sys.stdin.readline()[:-1])
	A = []
	cnt = 0
	ans = []
	zero = []
	one = []
	for comp in S:
		if not A:
			A.append([comp])
			ans.append(1)
			if comp == '0':
				zero.append(0)
			else:
				one.append(0)
		elif comp == '0':
			if one:
				zero.append(one.pop())
				ans.append(zero[-1] + 1)
			else:
				cnt += 1
				zero.append(cnt)
				ans.append(cnt + 1)
		elif comp == '1':
			if zero:
				one.append(zero.pop())
				ans.append(one[-1] + 1)
			else:
				cnt += 1
				one.append(cnt)
				ans.append(cnt + 1)
	print(cnt + 1)
	print(' '.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	s = input()
	dicti = {0: [], 1: []}
	ans = [-1] * n
	k = 0
	for z in range(n):
		e = int(s[z])
		if dicti[e]:
			ai = dicti[e].pop()
			dicti[1 - e].append(ai)
		else:
			k += 1
			dicti[1 - e].append(k)
			ai = k
		ans[z] = ai
	print(k)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(input())
	k = 0
	ans = []
	queue0 = []
	queue1 = []
	cnt = 0
	for i in range(n):
		if a[i] == '1':
			if len(queue0) == 0:
				cnt += 1
				queue1.append(cnt)
				ans.append(cnt)
				k += 1
			else:
				temp = queue0.pop(0)
				ans.append(temp)
				queue1.append(temp)
		elif len(queue1) == 0:
			cnt += 1
			queue0.append(cnt)
			ans.append(cnt)
			k += 1
		else:
			temp = queue1.pop(0)
			ans.append(temp)
			queue0.append(temp)
	print(k)
	print(' '.join([str(n) for n in ans]))


for cases in range(int(input())):
	n = int(input())
	s = input()
	dp = [1] * n
	start = s[0]
	count = 1
	for i in range(0, n):
		if s[i] == start:
			dp[i] = count
			count += 1
		else:
			dp[i] = count - 1
			count = count - 1
	min1 = min(dp)
	if min1 <= 0:
		for i in range(0, n):
			dp[i] = dp[i] + 1 + abs(min1)
	print(max(dp))
	print(*dp)


t = int(input())
for _ in range(t):
	n = int(input())
	b = input()
	arr_i = [0 for __ in range(n)]
	ends_w_zero = []
	ends_w_one = []
	new_sub = 1
	for i in range(n):
		if b[i] == '0':
			if len(ends_w_one) == 0:
				arr_i[i] = new_sub
				ends_w_zero.append(new_sub)
				new_sub += 1
			else:
				sub = ends_w_one.pop()
				arr_i[i] = sub
				ends_w_zero.append(sub)
		elif len(ends_w_zero) == 0:
			arr_i[i] = new_sub
			ends_w_one.append(new_sub)
			new_sub += 1
		else:
			sub = ends_w_zero.pop()
			arr_i[i] = sub
			ends_w_one.append(sub)
	print(new_sub - 1)
	print(' '.join([*map(str, arr_i)]))


for _ in range(int(input())):
	x = int(input())
	mylist = input()
	sz = []
	so = []
	count = 1
	out = []
	for i in range(x):
		if mylist[i] == '0':
			if so:
				sz.append(so.pop())
			else:
				sz.append(count)
				count += 1
			out.append(sz[-1])
		else:
			if sz:
				so.append(sz.pop())
			else:
				so.append(count)
				count += 1
			out.append(so[-1])
	print(count - 1)
	print(*out)


t = int(input())
while t:
	n = int(input())
	a = list(map(lambda x: int(x), input()))
	dic = {0: [], 1: []}
	for i in range(n):
		dic[a[i]].append(i)
	(i, j) = (0, 0)
	req = [-1 for i in range(n)]
	dic1 = {}
	while j < len(dic[1]) and i < len(dic[0]):
		if dic[0][i] < dic[1][j]:
			req[dic[0][i]] = dic[1][j]
			dic1[dic[1][j]] = True
			i += 1
		j += 1
	(i, j) = (0, 0)
	while i < len(dic[0]) and j < len(dic[1]):
		if dic[1][j] < dic[0][i]:
			req[dic[1][j]] = dic[0][i]
			dic1[dic[0][i]] = True
			j += 1
		i += 1
	sub = 1
	ans = [-1 for i in range(n)]
	dic2 = {}
	for i in range(n):
		if i not in dic2.keys():
			if req[i] == -1 and i not in dic1.keys():
				ans[i] = sub
				sub += 1
			else:
				dic2[i] = True
				j = i
				while req[j] != -1:
					ans[j] = sub
					j = req[j]
					dic2[j] = True
				ans[j] = sub
				dic2[j] = True
				sub += 1
	print(sub - 1)
	for i in ans:
		print(i, end=' ')
	print()
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = input()
	(a0, a1) = (0, 0)
	l = []
	for i in s:
		if i == '0':
			if a1 > 0:
				l.append(a0 + 1)
				a1 -= 1
				a0 += 1
			else:
				l.append(a0 + 1)
				a0 += 1
		elif a0 > 0:
			l.append(a0)
			a1 += 1
			a0 -= 1
		else:
			l.append(a1 + 1)
			a1 += 1
	print(a1 + a0)
	print(*l)


import os
import sys
from io import BytesIO, IOBase
from collections import deque

def main():
	for _ in range(int(input())):
		n = int(input())
		s = list(input())
		ans = []
		d = {0: deque(), 1: deque()}
		counter = 1
		for i in range(n):
			if s[i] == '0':
				if len(d[1]) == 0:
					d[0].append(counter)
					ans.append(counter)
					counter += 1
				else:
					popped = d[1].pop()
					d[0].append(popped)
					ans.append(popped)
			elif len(d[0]) == 0:
				d[1].append(counter)
				ans.append(counter)
				counter += 1
			else:
				popped = d[0].pop()
				d[1].append(popped)
				ans.append(popped)
		print(max(ans))
		print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import io, os
R = lambda : map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = []
	mx = 0
	ck = [[], []]
	for i in range(n):
		d = s[i] == '1'
		if len(ck[not d]) == 0:
			ck[d].append(mx + 1)
			mx += 1
			ans.append(mx)
		else:
			ck[d].append(ck[not d].pop())
			ans.append(ck[d][-1])
	print(mx)
	print(*ans)


for _ in range(int(input())):
	input()
	arr_0 = []
	arr_1 = []
	ans_str = ''
	MAX = 0
	for i in input():
		if i == '0':
			if len(arr_1) == 0:
				MAX += 1
				arr_0.append(MAX)
				ans_str += str(MAX) + ' '
			else:
				arr_0.append(arr_1.pop())
				ans_str += str(arr_0[-1]) + ' '
		if i == '1':
			if len(arr_0) == 0:
				MAX += 1
				arr_1.append(MAX)
				ans_str += str(MAX) + ' '
			else:
				arr_1.append(arr_0.pop())
				ans_str += str(arr_1[-1]) + ' '
	print(MAX)
	print(ans_str)


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	z = []
	o = []
	sz = 0
	so = 0
	ans = []
	num = 0
	for i in range(n):
		t = int(a[i])
		if t == 0:
			if so > 0:
				so -= 1
				temp = o.pop()
				ans.append(temp)
				z.append(temp)
				sz += 1
			else:
				num += 1
				z.append(num)
				sz += 1
				ans.append(num)
		elif sz > 0:
			sz -= 1
			temp = z.pop()
			ans.append(temp)
			o.append(temp)
			so += 1
		else:
			num += 1
			o.append(num)
			so += 1
			ans.append(num)
	print(num)
	for i in ans:
		print(i, end=' ')
	print('')


for _ in range(int(input())):
	N = int(input())
	s = list(input())
	last0 = []
	last1 = []
	ans = [0] * N
	count = 0
	for i in range(len(s)):
		if s[i] == '0':
			if len(last1) == 0:
				count += 1
				last0.append(count)
				ans[i] = count
			else:
				last0.append(last1[-1])
				ans[i] = last1[-1]
				last1.pop()
		elif len(last0) == 0:
			count += 1
			last1.append(count)
			ans[i] = count
		else:
			last1.append(last0[-1])
			ans[i] = last0[-1]
			last0.pop()
	print(count)
	print(*ans)


T = int(input())
for t in range(T):
	n = int(input())
	s = input()
	i = 0
	end = [[], []]
	res = []
	for c in s:
		v = int(c)
		if end[1 - v]:
			end[v].append(end[1 - v].pop())
		else:
			i += 1
			end[v].append(i)
		res.append(end[v][-1])
	print(i)
	print(*res)


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = len(li) - 1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def mex(li):
	check = [0] * 1001
	for i in li:
		check[i] += 1
	for i in range(len(check)):
		if check[i] == 0:
			return i

def sumdigits(n):
	ans = 0
	while n != 0:
		ans += n % 10
		n //= 10
	return ans

def product(li):
	ans = 1
	for i in li:
		ans *= i
	return ans

def maxpower(n, k):
	cnt = 0
	while n > 1:
		cnt += 1
		n //= k
	return cnt

def knapsack(li, sumi, s, n, dp):
	if s == sumi // 2:
		return 1
	elif n == 0:
		return 0
	elif dp[n][s] != -1:
		return dp[n][s]
	else:
		if li[n - 1] <= s:
			dp[n][s] = knapsack(li, sumi, s - li[n - 1], n - 1, dp) or knapsack(li, sumi, s, n - 1, dp)
		else:
			dp[n][s] = knapsack(li, sumi, s, n - 1, dp)
		return dp[n][s]

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum
from math import *
from collections import deque
max_steps = 100005
for _ in range(int(input())):
	n = int(input())
	s = input()
	checker = [[], []]
	seq_num = 0
	ans = []
	for j in s:
		i = int(j)
		if len(checker[i]):
			transfer = checker[i].pop()
			checker[1 - i].append(transfer)
			ans.append(checker[1 - i][-1])
		else:
			seq_num += 1
			checker[1 - i].append(seq_num)
			ans.append(seq_num)
	print(seq_num)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = []
	zeros = []
	ones = []
	if s[0] == '1':
		ones = [1]
	else:
		zeros = [1]
	count = 1
	for i in s:
		if i == '0':
			if len(zeros):
				l.append(zeros.pop(-1))
				ones.append(l[-1])
			else:
				count += 1
				l.append(count)
				ones.append(count)
		elif len(ones):
			l.append(ones.pop(-1))
			zeros.append(l[-1])
		else:
			count += 1
			l.append(count)
			zeros.append(count)
	print(count)
	print(' '.join(map(str, l)))


from collections import deque

def solve(n, s):
	res = []
	dq0 = deque()
	dq1 = deque()
	idx = 1
	for c in s:
		if c == '0':
			if len(dq1) > 0:
				cur = dq1.popleft()
				dq0.append(cur)
				res.append(cur)
			else:
				dq0.append(idx)
				res.append(idx)
				idx += 1
		elif len(dq0) > 0:
			cur = dq0.popleft()
			dq1.append(cur)
			res.append(cur)
		else:
			dq1.append(idx)
			res.append(idx)
			idx += 1
	print(idx - 1)
	print(' '.join(map(str, res)))
	return
t = int(input())
for i in range(0, t):
	n = int(input())
	s = input()
	solve(n, s)


def main():
	t = Iint()
	for _ in range(t):
		n = Iint()
		s = I()
		ends_with_1_dict = set()
		ends_with_0_dict = set()
		ans_array = [0] * n
		ans_count = 0
		for (i, si) in en(s):
			if si == '0':
				if not ends_with_1_dict:
					ans_count += 1
					ends_with_0_dict.add(ans_count)
					ans_array[i] = ans_count
				else:
					x = ends_with_1_dict.pop()
					ans_array[i] = x
					ends_with_0_dict.add(x)
			elif si == '1':
				if not ends_with_0_dict:
					ans_count += 1
					ends_with_1_dict.add(ans_count)
					ans_array[i] = ans_count
				else:
					x = ends_with_0_dict.pop()
					ans_array[i] = x
					ends_with_1_dict.add(x)
		print(ans_count)
		Plist(ans_array)
FIO = 10

def I():
	return input()

def Iint():
	return int(input())

def Ilist():
	return list(map(int, input().split()))

def Imap():
	return map(int, input().split())

def Plist(li, s=' '):
	print(s.join(map(str, li)))
en = enumerate

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
else:
	from io import BytesIO, IOBase
	import sys
	import os
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	n = int(input())
	st = input()
	end0 = []
	end1 = []
	cnt = 1
	arr = []
	for (idx, s) in enumerate(st):
		if s == '0':
			if not end1:
				end0.append(cnt)
				arr.append(cnt)
				cnt += 1
			else:
				num = end1.pop()
				end0.append(num)
				arr.append(num)
		elif not end0:
			end1.append(cnt)
			arr.append(cnt)
			cnt += 1
		else:
			num = end0.pop()
			end1.append(num)
			arr.append(num)
	print(len(end0) + len(end1))
	print(*arr)


import math
import time
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from queue import PriorityQueue
import sys
t = int(input())
for _ in range(t):
	n = int(stdin.readline())
	s = input()
	end_zero = []
	end_one = []
	ans = []
	curr = 0
	for i in s:
		if i == '0':
			toadd = curr + 1
			if len(end_one) > 0:
				toadd = end_one.pop()
				curr -= 1
			curr += 1
			ans.append(toadd)
			end_zero.append(toadd)
		else:
			toadd = curr + 1
			if len(end_zero) > 0:
				toadd = end_zero.pop()
				curr -= 1
			curr += 1
			ans.append(toadd)
			end_one.append(toadd)
	print(len(end_one) + len(end_zero))
	print(*ans)


from collections import deque
num_queries = int(input())
for query in range(num_queries):
	arr_len = int(input())
	sequence = str(input())
	subsequences_0 = deque()
	subsequences_1 = deque()
	subsequence_idxs = deque()
	max_subsequence_idx = 0
	for bit in sequence:
		if bit == '0':
			if len(subsequences_1) > 0:
				subsequence_idx = subsequences_1.pop()
				subsequences_0.append(subsequence_idx)
				subsequence_idxs.append(subsequence_idx)
			else:
				subsequence_idx = max_subsequence_idx + 1
				max_subsequence_idx = subsequence_idx
				subsequences_0.append(subsequence_idx)
				subsequence_idxs.append(subsequence_idx)
		elif len(subsequences_0) > 0:
			subsequence_idx = subsequences_0.pop()
			subsequences_1.append(subsequence_idx)
			subsequence_idxs.append(subsequence_idx)
		else:
			subsequence_idx = max_subsequence_idx + 1
			max_subsequence_idx = subsequence_idx
			subsequences_1.append(subsequence_idx)
			subsequence_idxs.append(subsequence_idx)
	print(max_subsequence_idx)
	subsequence_idxs = list(map(str, subsequence_idxs))
	print(' '.join(subsequence_idxs))


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input()]
	ans = []
	c = 0
	d = {0: [], 1: []}
	for i in range(n):
		if len(d[a[i] ^ 1]) > 0:
			temp = d[a[i] ^ 1].pop()
			d[a[i]].append(temp)
			ans.append(temp)
		else:
			c += 1
			d[a[i]].append(c)
			ans.append(c)
	print(c)
	print(*ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = stdin.readline().strip()
	d = {'0': [], '1': []}
	if s[0] == '0':
		d['0'].append(1)
	else:
		d['1'].append(1)
	ans = [1]
	j = 1
	for i in range(1, n):
		if s[i] == '0':
			if len(d['1']) == 0:
				j += 1
				d['0'].append(j)
			else:
				d['0'].append(d['1'][-1])
				del d['1'][-1]
		elif len(d['0']) == 0:
			j += 1
			d['1'].append(j)
		else:
			d['1'].append(d['0'][-1])
			del d['0'][-1]
		ans.append(d[s[i]][-1])
	print(max(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	k = 0
	o = []
	last_chars = [[], []]
	for c in s:
		intc = int(c)
		oppc = 1 if c == '0' else 0
		if len(last_chars[oppc]) > 0:
			a = last_chars[oppc].pop()
			last_chars[intc].append(a)
			o.append(a)
		else:
			k += 1
			last_chars[intc].append(k)
			o.append(k)
	print(k)
	print(' '.join(map(str, o)))


for _ in range(int(input())):
	n = int(input())
	l = list(input())
	pos0 = []
	pos1 = []
	ans = [0 for x in range(n)]
	for i in range(n):
		newpos = len(pos0) + len(pos1)
		if l[i] == '0':
			if len(pos1) == 0:
				pos0.append(newpos)
			else:
				newpos = pos1[-1]
				pos1.pop()
				pos0.append(newpos)
		elif len(pos0) == 0:
			pos1.append(newpos)
		else:
			newpos = pos0[-1]
			pos0.pop()
			pos1.append(newpos)
		ans[i] = newpos + 1
	print(len(pos0) + len(pos1))
	print(*ans)


import math
from decimal import Decimal
import heapq
import copy
import heapq
from collections import deque
from collections import defaultdict

def na():
	n = int(input())
	b = [int(x) for x in input().split()]
	return (n, b)

def nab():
	n = int(input())
	b = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	return (n, b, c)

def dv():
	(n, m) = map(int, input().split())
	return (n, m)

def da():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	return (n, m, a)

def dva():
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	return (n, m, b)

def eratosthenes(n):
	sieve = list(range(n + 1))
	for i in sieve:
		if i > 1:
			for j in range(i + i, len(sieve), i):
				sieve[j] = 0
	return sorted(set(sieve))

def lol(lst, k):
	k = k % len(lst)
	ret = [0] * len(lst)
	for i in range(len(lst)):
		if i + k < len(lst) and i + k >= 0:
			ret[i] = lst[i + k]
		if i + k >= len(lst):
			ret[i] = lst[i + k - len(lst)]
		if i + k < 0:
			ret[i] = lst[i + k + len(lst)]
	return ret

def nm():
	n = int(input())
	b = [int(x) for x in input().split()]
	m = int(input())
	c = [int(x) for x in input().split()]
	return (n, b, m, c)

def dvs():
	n = int(input())
	m = int(input())
	return (n, m)

def fact(n):
	tc = []
	ans = {}
	d = 2
	while d * d <= n:
		if n % d == 0:
			tc.append(d)
			n //= d
		else:
			d += 1
	if n > 1:
		tc.append(n)
	for i in tc:
		ans[i] = ans.get(i, 0) + 1
	return ans

def to_zero(n, s):
	lst = s[0]
	ans = []
	for i in range(n):
		if lst == s[i]:
			continue
		elif lst == '0':
			lst = '1'
			ans.append(i)
		else:
			lst = '0'
			ans.append(i)
	if lst == '1':
		ans.append(n)
	return ans
for _ in range(int(input())):
	n = int(input())
	s = input()
	tc = 1
	lst = s[0]
	a = [1]
	kon1 = []
	kon0 = []
	if s[0] == '1':
		kon1.append(1)
	else:
		kon0.append(1)
	for i in range(1, n):
		if s[i] == '0':
			if len(kon1) != 0:
				lstt = kon1.pop()
				kon0.append(lstt)
				a.append(lstt)
			else:
				tc += 1
				kon0.append(tc)
				a.append(tc)
			lst = '0'
		else:
			if len(kon0) != 0:
				lstt = kon0.pop()
				kon1.append(lstt)
				a.append(lstt)
			else:
				tc += 1
				kon1.append(tc)
				a.append(tc)
			lst = '1'
	print(tc)
	print(*a)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input()]
	z = [[], []]
	pos = []
	cnt = 0
	for i in range(n):
		x = a[i]
		if len(z[1 - x]) == 0:
			cnt += 1
			z[x].append(cnt)
			pos.append(cnt)
		else:
			new_pos = z[1 - x].pop()
			z[x].append(new_pos)
			pos.append(new_pos)
	print(cnt)
	for i in pos:
		print(i, end=' ')
	print()


from collections import deque
from math import *
import heapq
from random import *
import sys
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	l = []
	for j in range(len(s)):
		l.append(int(s[j]))
	d = {}
	d[0] = []
	d[1] = []
	LEVEL = 1
	ans = [0] * len(l)
	for j in range(len(l)):
		if len(d[1 - l[j]]) <= 0:
			d[l[j]].append(LEVEL)
			LEVEL += 1
		else:
			d[l[j]].append(d[1 - l[j]][-1])
			d[1 - l[j]].pop()
		ans[j] = d[l[j]][-1]
	print(LEVEL - 1)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	st = input()
	dic = {}
	ct = []
	one = []
	zero = []
	ch = 0
	for i in range(len(st)):
		c = st[i]
		if c == '1':
			if len(zero) > 0:
				k = zero[-1]
				ct.append(k)
				one.append(k)
				zero.pop()
				dic[k] = 1
			else:
				ch += 1
				one.append(ch)
				ct.append(ch)
				dic[ch] = 1
		elif c == '0':
			if len(one) > 0:
				k = one[-1]
				ct.append(k)
				zero.append(k)
				one.pop()
				dic[k] = 1
			else:
				ch += 1
				zero.append(ch)
				ct.append(ch)
				dic[ch] = 0
	print(max(ct))
	print(*ct)


t = int(input())
for _ in range(t):
	n = int(input())
	s = map(int, input())
	zeros = []
	ones = []
	count = 0
	ans = []
	for d in s:
		if d == 0:
			if zeros:
				ans.append(zeros[-1])
				ones.append(zeros.pop())
			else:
				count += 1
				ans.append(count)
				ones.append(count)
		elif ones:
			ans.append(ones[-1])
			zeros.append(ones.pop())
		else:
			count += 1
			ans.append(count)
			zeros.append(count)
	print(count)
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = list(input())
	s = list(map(int, s))
	dp = [1] * n
	dict1 = {0: [], 1: []}
	max1 = 1
	for j in range(1, n):
		if s[j - 1] == s[j]:
			if s[j] == 0:
				if dict1[1] == []:
					dp[j] = max1 + 1
					max1 += 1
					dict1[0].append(max1)
				else:
					dp[j] = dict1[1][0]
					dict1[1].pop(0)
					dict1[0].append(dp[j])
			elif dict1[0] == []:
				dp[j] = max1 + 1
				max1 += 1
				dict1[1].append(max1)
			else:
				dp[j] = dict1[0][0]
				dict1[0].pop(0)
				dict1[1].append(dp[j])
		else:
			dp[j] = 1
	print(max(dp))
	for j in range(n):
		print(dp[j], end=' ')
	print('')


from queue import Queue
for _ in range(int(input())):
	n = int(input())
	s = input()
	l = [0] * n
	zerostack = [0]
	onestack = [0]
	for i in range(n):
		if s[i] == '0':
			if onestack[-1] == 0:
				l[i] = zerostack[-1] + 1
				zerostack.append(zerostack[-1] + 1)
			else:
				l[i] = onestack.pop()
				if l[i] > zerostack[-1]:
					zerostack.append(l[i])
				else:
					temp = zerostack.pop()
					zerostack.append(l[i])
					zerostack.append(temp)
		elif zerostack[-1] == 0:
			l[i] = onestack[-1] + 1
			onestack.append(onestack[-1] + 1)
		else:
			l[i] = zerostack.pop()
			if l[i] > onestack[-1]:
				onestack.append(l[i])
			else:
				temp = onestack.pop()
				onestack.append(l[i])
				onestack.append(temp)
	print(max(l))
	print(*l)


from heapq import heapify, heappush, heappop
q = int(input())
for i in range(q):
	n = int(input())
	lst = input()
	lst = [int(x) for x in lst]
	mx = 1
	ret = [0 for i in range(n)]
	z = []
	o = []
	for i in range(n):
		if lst[i] == 1:
			if len(o) == 0:
				ret[i] = mx
				heappush(z, mx)
				mx += 1
			else:
				idx = heappop(o)
				ret[i] = idx
				heappush(z, idx)
		elif len(z) == 0:
			ret[i] = mx
			heappush(o, mx)
			mx += 1
		else:
			idx = heappop(z)
			ret[i] = idx
			heappush(o, idx)
	print(max(ret))
	print(*ret, sep=' ')


import sys
from collections import deque
input = sys.stdin.readline
for t in range(int(input())):
	n = int(input())
	s = input()
	ans = [1]
	q0 = deque()
	q1 = deque()
	if s[0] == '0':
		q0.append(0)
	else:
		q1.append(0)
	r = 1
	for i in range(1, n):
		if s[i] == '0':
			if q1:
				k = q1.popleft()
				ans.append(k + 1)
				q0.append(k)
			else:
				q0.append(r)
				r += 1
				ans.append(r)
		elif q0:
			k = q0.popleft()
			ans.append(k + 1)
			q1.append(k)
		else:
			q1.append(r)
			r += 1
			ans.append(r)
	print(r)
	print(*ans)


T = int(input())
for _ in range(T):
	N = int(input())
	s = input()
	A = [-1 for i in range(N)]
	(zol, onl) = ([], [])
	(zo, on) = (0, 0)
	cs = 0
	for i in range(N):
		if s[i] == '0':
			if on > 0:
				on = on - 1
				A[i] = onl.pop()
			else:
				cs = cs + 1
				A[i] = cs
			zol.append(A[i])
			zo = zo + 1
		else:
			if zo > 0:
				zo = zo - 1
				A[i] = zol.pop()
			else:
				cs = cs + 1
				A[i] = cs
			onl.append(A[i])
			on = on + 1
	print(cs)
	print(*A)


for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	ans = []
	need = 0
	zero_unpaired = set()
	one_unpaired = set()
	for i in range(n):
		if s[i] == '1':
			if zero_unpaired:
				curr = zero_unpaired.pop()
				ans.append(curr)
			else:
				need += 1
				ans.append(need)
				one_unpaired.add(need)
				curr = need
			one_unpaired.add(curr)
		else:
			if one_unpaired:
				curr = one_unpaired.pop()
				ans.append(curr)
			else:
				need += 1
				ans.append(need)
				zero_unpaired.add(need)
				curr = need
			zero_unpaired.add(curr)
	print(need)
	print(*ans)


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().strip()

def get_strs():
	return get_str().split(' ')

def flat_list(arr):
	return [item for subarr in arr for item in subarr]

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	return p

def solve_a():
	n = get_int()
	a = get_ints()
	a.sort()
	jumps = [a[i + 1] - a[i] for i in range(n - 1) if a[i + 1] - a[i] > 1]
	if len(jumps) > 0:
		return 'NO'
	else:
		return 'YES'

def solve_b():
	n = get_int()
	a = get_ints()
	b = get_ints()
	return sum([max(c - min(a), d - min(b)) for (c, d) in zip(a, b)])

def solve_c():
	n = get_int()
	w = get_ints()
	W = Counter(w)
	combos = defaultdict(int)
	best = 0
	for (k, v) in W.items():
		for (k2, v2) in W.items():
			if k == k2:
				combos[k + k2] += v // 2
			elif k2 > k:
				continue
			else:
				combos[k + k2] += min(v, v2)
			best = max(best, combos[k + k2])
	return best

def solve_d():
	n = get_int()
	s = get_str()
	h = [[], []]
	ans = []
	pend = 1
	for c in s:
		x = int(c)
		if not h[1 - x]:
			h[x].append(pend)
			pend += 1
		else:
			h[x].append(h[1 - x].pop())
		ans.append(h[x][-1])
	print(pend - 1)
	print(*ans)
t = get_int()
for _ in range(t):
	solve_d()


import sys
import math
from collections import defaultdict, Counter, deque

def solve(test):
	n = int(input())
	s = list(input())
	(ones, zeros) = ([], [])
	rec = [None] * n
	k = 1
	mx = 1
	for i in range(n):
		if i == 0:
			rec[i] = k
		elif s[i] != s[i - 1]:
			rec[i] = rec[i - 1]
		else:
			p = k
			if s[i] == '1':
				if ones:
					k = ones.pop()
				else:
					k = mx + 1
			elif zeros:
				k = zeros.pop()
			else:
				k = mx + 1
			rec[i] = k
			if s[i - 1] == '0':
				ones.append(p)
			else:
				zeros.append(p)
		mx = max(mx, k)
	print(mx)
	rec = [str(x) for x in rec]
	print(' '.join(rec))
test_cases = int(input())
for t in range(1, test_cases + 1):
	solve(t)


def solve():
	n = int(input())
	bits = input()
	carry_zero = []
	carry_one = []
	teams = []
	counter = 0
	for bit in bits:
		if bit == '0':
			if carry_one:
				team = carry_one.pop()
			else:
				counter += 1
				team = str(counter)
			carry_zero.append(team)
		if bit == '1':
			if carry_zero:
				team = carry_zero.pop()
			else:
				counter += 1
				team = str(counter)
			carry_one.append(team)
		teams.append(team)
	place = ' '.join(teams)
	return '{}\n{}'.format(counter, place)
n = int(input())
for i in range(n):
	result = solve()
	print(result)


import time, math as mt, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return
mod = 10 ** 9 + 7

def solve():
	n = II()
	s = input()
	if n == 1:
		print(1)
		print(1)
		return
	(sub0, sub1) = (deque(), deque())
	pos = [-1] * n
	v = 1
	for i in range(n):
		if s[i] == '0':
			if sub1:
				x = sub1.pop()
				sub0.append(x)
				pos[i] = x
			else:
				sub0.append(v)
				pos[i] = v
				v += 1
		elif sub0:
			x = sub0.pop()
			sub1.append(x)
			pos[i] = x
		else:
			sub1.append(v)
			pos[i] = v
			v += 1
	print(max(pos))
	print(*pos)
t = II()
for i in range(t):
	solve()


tests = int(input())
for test in range(tests):
	n = int(input())
	A = input()
	Z = []
	O = []
	M = []
	for i in A:
		if i == '0':
			if len(O) == 0:
				Z.append(len(Z) + 1)
			else:
				Z.append(O.pop())
			M.append(Z[-1])
		elif i == '1':
			if len(Z) == 0:
				O.append(len(O) + 1)
			else:
				O.append(Z.pop())
			M.append(O[-1])
	print(max(M))
	print(' '.join(map(str, M)))


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
for _ in range(II()):
	n = II()
	aa = [int(c) for c in SI()]
	last = [[], []]
	cnt = 1
	now = 1
	ans = [-1] * n
	for i in range(n - 1):
		ans[i] = now
		if aa[i] == aa[i + 1]:
			a = aa[i]
			last[a].append(now)
			if last[1 - a]:
				now = last[1 - a].pop()
			else:
				cnt += 1
				now = cnt
	ans[n - 1] = now
	print(cnt)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	l = []
	sub_0 = []
	sub_1 = []
	for i in range(0, n):
		if s[i] == '0':
			if len(sub_1) > 0:
				sub_0.append(sub_1.pop())
			else:
				sub_0.append(len(sub_0) + len(sub_1) + 1)
			l.append(sub_0[-1])
		else:
			if len(sub_0) > 0:
				sub_1.append(sub_0.pop())
			else:
				sub_1.append(len(sub_0) + len(sub_1) + 1)
			l.append(sub_1[-1])
	print(max(l))
	print(*l)


import sys
import math
from collections import defaultdict
import heapq
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	s = sys.stdin.readline()[:-1]
	ans = [0 for x in range(n)]
	(end0, end1) = ([], [])
	(cnt0, cnt1) = (0, 0)
	cur = 0
	for i in range(n):
		if s[i] == '1':
			if cnt0 > 0:
				x = end0.pop()
				end1.append(x)
				cnt0 -= 1
				cnt1 += 1
				ans[i] = x
			else:
				cur += 1
				ans[i] = cur
				end1.append(cur)
				cnt1 += 1
		elif cnt1 > 0:
			x = end1.pop()
			end0.append(x)
			cnt1 -= 1
			cnt0 += 1
			ans[i] = x
		else:
			cur += 1
			ans[i] = cur
			end0.append(cur)
			cnt0 += 1
	print(cur)
	print(*ans)


t = int(input())
while t:
	n = int(input())
	s = input()
	check = -1
	count0 = []
	count1 = []
	if s[0] == '0':
		check = 0
		count0.append(1)
	else:
		check = 1
		count1.append(1)
	l2 = []
	l2.append(1)
	curr = 1
	for i in range(1, n):
		if s[i] == '0':
			if len(count1) > 0:
				a = count1.pop()
				l2.append(a)
				count0.append(a)
			else:
				curr = curr + 1
				l2.append(curr)
				count0.append(curr)
		elif len(count0) > 0:
			a = count0.pop()
			l2.append(a)
			count1.append(a)
		else:
			curr = curr + 1
			l2.append(curr)
			count1.append(curr)
	print(curr)
	print(*l2)
	t = t - 1


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	ans = [1] * n
	num1 = 0
	seq1 = []
	num0 = 0
	seq0 = []
	for i in range(n):
		if s[i] == '0':
			num0 += 1
			if num1 == 0:
				seq0 += [num0]
				ans[i] = num0
			else:
				seq0 += [seq1.pop()]
				ans[i] = seq0[-1]
				num1 -= 1
		else:
			num1 += 1
			if num0 == 0:
				seq1 += [num1]
				ans[i] = num1
			else:
				seq1 += [seq0.pop()]
				ans[i] = seq1[-1]
				num0 -= 1
	print(max(ans))
	print(' '.join(map(str, ans)))


def solve():
	n = int(input())
	s = input()
	(z, o) = ([], [])
	c = 0
	ans = []

	def add(x):
		nonlocal z, o, c, ans
		(u, v) = (z, o)
		if x == 0:
			(u, v) = (v, u)
		if u:
			w = u.pop()
			ans.append(w)
			v.append(w)
		else:
			c += 1
			ans.append(c)
			v.append(c)
	for i in s:
		add(int(i))
	print(c)
	print(*ans)
t = int(input())
for _ in range(t):
	solve()


from sys import stdin
input = lambda : stdin.readline().strip()
cases = int(input())
for t in range(cases):
	n = int(input())
	s = input()
	d = {'0': [], '1': []}
	v = []
	c = 1
	for i in s:
		if i == '0':
			if d['1']:
				val = d['1'].pop()
				d['0'].append(val)
			else:
				d['0'].append(c)
				c += 1
		elif d['0']:
			val = d['0'].pop()
			d['1'].append(val)
		else:
			d['1'].append(c)
			c += 1
		v.append(d[i][-1])
	print(max(v))
	print(*v)


import sys
for _ in range(int(input())):
	n = int(input())
	s = input()
	dic = {'1': [], '0': []}
	count = 1
	res = [None] * n
	res[0] = 1
	if s[0] == '0':
		dic['1'].append(count)
	else:
		dic['0'].append(count)
	for i in range(1, n):
		if dic[s[i]]:
			x = dic[s[i]].pop()
			res[i] = x
			if s[i] == '0':
				dic['1'].append(x)
			else:
				dic['0'].append(x)
		else:
			count += 1
			res[i] = count
			if s[i] == '0':
				dic['1'].append(count)
			else:
				dic['0'].append(count)
	print(count)
	sys.stdout.write(' '.join(map(str, res)) + '\n')


import sys
t = int(input())
for i in range(0, t):
	n = int(input())
	arr = input()
	ans = []
	onestack = []
	zerostack = []
	ind = {}
	seqno = 1
	for i in range(0, n):
		if arr[i] == '0':
			if not onestack:
				zerostack.append(seqno)
				ind[i] = seqno
				seqno += 1
			else:
				ele = onestack.pop()
				ind[i] = ele
				zerostack.append(ele)
		elif not zerostack:
			onestack.append(seqno)
			ind[i] = seqno
			seqno += 1
		else:
			ele = zerostack.pop()
			ind[i] = ele
			onestack.append(ele)
	print(seqno - 1)
	for i in range(0, n):
		print(ind.get(i), end=' ')
	print()


from sys import stdin, stdout, setrecursionlimit
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007
tc = ii1()
for _ in range(tc):
	n = ii1()
	s = is1()
	(zero, one) = (deque([]), deque([]))
	res = []
	grp = 0
	for i in s:
		if i == '1':
			if len(zero):
				cur = zero.popleft()
				res.append(cur)
				one.append(cur)
			else:
				one.append(grp + 1)
				res.append(grp + 1)
				grp += 1
		elif len(one):
			cur = one.popleft()
			res.append(cur)
			zero.append(cur)
		else:
			zero.append(grp + 1)
			res.append(grp + 1)
			grp += 1
	print(max(res))
	print(*res)


from sys import stdin
input = lambda : stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	ans = [1] * n
	s = input()
	needzero = set()
	needone = set()
	if s[0] == '0':
		needone.add(1)
	else:
		needzero.add(1)
	cur = 2
	for i in range(1, n):
		if s[i] == '0':
			if len(needzero) == 0:
				ans[i] = cur
				needone.add(cur)
				cur += 1
			else:
				f = needzero.pop()
				ans[i] = f
				needone.add(f)
		elif len(needone) == 0:
			ans[i] = cur
			needzero.add(cur)
			cur += 1
		else:
			f = needone.pop()
			ans[i] = f
			needzero.add(f)
	print(cur - 1)
	print(*ans)


def arri():
	return list(map(int, input().split()))
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(input())
	(haveZero, haveOne) = ([], [])
	ans = [0] * n
	val = 0
	for i in range(n):
		if arr[i] == '1' and haveZero:
			ans[i] = haveZero.pop()
			haveOne.append(ans[i])
		elif arr[i] == '1':
			val += 1
			ans[i] = val
			haveOne.append(val)
		if arr[i] == '0' and haveOne:
			ans[i] = haveOne.pop()
			haveZero.append(ans[i])
		elif arr[i] == '0':
			val += 1
			ans[i] = val
			haveZero.append(val)
	print(max(ans))
	print(' '.join(map(str, ans)))


from collections import defaultdict
t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	a = input()
	d = defaultdict(lambda : 0)
	d[0] = 1
	count = 1
	index0 = []
	index1 = []
	if a[0] == '0':
		index0.append(count)
	else:
		index1.append(count)
	for i in range(1, len(a)):
		if a[i] == '0':
			if len(index1) == 0:
				count += 1
				d[i] = count
				index0.append(count)
			else:
				d[i] = index1[0]
				index0.append(index1[0])
				index1.pop(0)
		elif len(index0) == 0:
			count += 1
			d[i] = count
			index1.append(count)
		else:
			d[i] = index0[0]
			index1.append(index0[0])
			index0.pop(0)
	print(count)
	for i in d:
		print(d[i], end=' ')
	print()


def solve():
	n = int(input())
	s = input()
	total = 0
	ans = [0 for _ in range(n)]
	min_k = 0
	max_k = 0
	for ss in s:
		if ss == '1':
			total += 1
			max_k = max(max_k, total)
		else:
			total -= 1
			min_k = min(min_k, total)
	k = max_k - min_k
	print(k)
	plus = abs(min_k)
	total = 0
	for (i, ss) in enumerate(s):
		if ss == '1':
			total += 1
			ans[i] = total + plus
		else:
			ans[i] = total + plus
			total -= 1
	print(*ans)
t = int(input())
for _ in range(t):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	zero_queue = []
	one_queue = []
	count = 0
	ans = []
	for i in range(n):
		if s[i] == '0':
			if len(zero_queue) > 0:
				seq = zero_queue.pop()
			else:
				count += 1
				seq = count
			one_queue.append(seq)
		else:
			if len(one_queue) > 0:
				seq = one_queue.pop()
			else:
				count += 1
				seq = count
			zero_queue.append(seq)
		ans.append(seq)
	print(count)
	print(' '.join(map(str, ans)))


t = int(input())
for i in range(t):
	n = int(input())
	a = []
	s = input()
	x = set()
	y = set()
	for c in s:
		e = 0
		if c == '0':
			if len(y) == 0:
				e = len(x) + len(y) + 1
			else:
				for e in y:
					break
				y.remove(e)
			a.append(e)
			x.add(e)
		else:
			if len(x) == 0:
				e = len(x) + len(y) + 1
			else:
				for e in x:
					break
				x.remove(e)
			a.append(e)
			y.add(e)
	print(len(x) + len(y))
	print(*a)


from collections import deque
t = int(input())
for testcase in range(t):
	n = int(input())
	s = input()
	z = deque()
	o = deque()
	st = 1
	ans = [0] * n
	for i in range(len(s)):
		c = s[i]
		if c == '0':
			if len(z) == 0:
				ans[i] = st
				o.append(st)
				st += 1
			else:
				ind = z.pop()
				ans[i] = ind
				o.append(ind)
		elif len(o) == 0:
			ans[i] = st
			z.append(st)
			st += 1
		else:
			ind = o.pop()
			ans[i] = ind
			z.append(ind)
	print(st - 1)
	for i in range(len(ans)):
		if i < len(ans) - 1:
			print(ans[i], end=' ')
		else:
			print(ans[i])


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	endwith1 = set()
	endwith0 = set()
	if s[0] == '1':
		endwith1.add(1)
	else:
		endwith0.add(1)
	res = [1]
	t = 1
	maxt = 1
	for i in range(1, n):
		if s[i] != s[i - 1]:
			res.append(t)
			if s[i] == '1':
				endwith1.add(t)
				if t in endwith0:
					endwith0.remove(t)
			else:
				endwith0.add(t)
				if t in endwith1:
					endwith1.remove(t)
		else:
			if s[i] == '1' and len(endwith0) == 0 or (s[i] == '0' and len(endwith1) == 0):
				maxt += 1
				t = maxt
				all = s[i]
				if s[i] == '1':
					endwith1.add(t)
					if t in endwith0:
						endwith0.remove(t)
				else:
					endwith0.add(t)
					if t in endwith1:
						endwith1.remove(t)
			elif s[i] == '1':
				t = endwith0.pop()
				endwith1.add(t)
			else:
				t = endwith1.pop()
				endwith0.add(t)
			res.append(t)
	print(maxt)
	print(*res)


T = int(input())
while T > 0:
	n = int(input())
	arr = input()
	res = 0
	ans = [0] * n
	end_1 = []
	end_0 = []
	for i in range(n):
		if arr[i] == '0':
			if len(end_1) == 0:
				res += 1
				ans[i] = res
				end_0.append(res)
			else:
				tmp = end_1.pop(0)
				ans[i] = tmp
				end_0.append(tmp)
		elif len(end_0) == 0:
			res += 1
			ans[i] = res
			end_1.append(res)
		else:
			tmp = end_0.pop(0)
			ans[i] = tmp
			end_1.append(tmp)
	print(res)
	print(*ans)
	T -= 1


from collections import deque as dq
for t in range(int(input())):
	n = int(input())
	last = {0: dq(), 1: dq()}
	ch = [0 if c == '0' else 1 for c in input()]
	for i in range(n):
		c = ch[i]
		if len(last[c ^ 1]) == 0:
			last[c].append([i])
		else:
			seq = last[c ^ 1].pop()
			seq.append(i)
			last[c].append(seq)
	(group, idx) = ([0] * n, 1)
	for bit in range(2):
		for p in last[bit]:
			for i in p:
				group[i] = idx
			idx += 1
	print(len(last[0]) + len(last[1]))
	print(' '.join((str(r) for r in group)))


import math, sys
input = sys.stdin.readline
S = lambda : input().rstrip()
I = lambda : int(S())
M = lambda : map(int, S().split())
L = lambda : list(M())
mod1 = 1000000007
mod2 = 998244353
for _ in range(I()):
	n = I()
	s = S()
	o = []
	z = []
	ans = 0
	res = [0] * n
	for i in range(n):
		if s[i] == '0':
			if len(o) == 0:
				z.append(ans + 1)
				ans += 1
			else:
				z.append(o.pop())
			res[i] = z[-1]
		else:
			if len(z) == 0:
				o.append(ans + 1)
				ans += 1
			else:
				o.append(z.pop())
			res[i] = o[-1]
	print(ans)
	print(*res)


from sys import stdin
from collections import deque
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = list(input().strip())
	subs = [[0, deque([])], [0, deque([])]]
	sn = 1
	for i in range(n):
		if s[i] == '0':
			if subs[1][0] >= 1:
				subs[1][0] -= 1
				subs[0][0] += 1
				s[i] = subs[1][1].pop()
				subs[0][1].append(s[i])
			else:
				subs[0][0] += 1
				s[i] = sn
				subs[0][1].append(sn)
				sn += 1
		elif subs[0][0] >= 1:
			subs[0][0] -= 1
			subs[1][0] += 1
			s[i] = subs[0][1].pop()
			subs[1][1].append(s[i])
		else:
			subs[1][0] += 1
			subs[1][1].append(sn)
			s[i] = sn
			sn += 1
	print(sn - 1)
	print(' '.join(map(str, s)))


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def get_next():
	global z_start, zero, one, idx
	if z_start:
		if len(one) == 0:
			return -1
		new = one.bisect_left(idx)
		return new if new != len(one) else -1
	if len(zero) == 0:
		return -1
	new = zero.bisect_left(idx)
	return new if new != len(zero) else -1
for case in range(1, itg() + 1):
	n = itg()
	s = inp()
	zero = []
	one = []
	for i in range(n):
		if s[i] == '0':
			zero.append(i)
		else:
			one.append(i)
	zero = SortedList(zero)
	one = SortedList(one)
	ans = [0] * n
	t = 1
	while len(zero) != 0 or len(one) != 0:
		if len(one) == 0:
			z_start = True
		elif len(zero) == 0:
			z_start = False
		else:
			z_start = zero[0] < one[0]
		if z_start:
			idx = zero.pop(0)
		else:
			idx = one.pop(0)
		ans[idx] = t
		idx = get_next()
		while idx != -1:
			if z_start:
				idx = one.pop(idx)
			else:
				idx = zero.pop(idx)
			ans[idx] = t
			z_start ^= 1
			idx = get_next()
		t += 1
	print(t - 1)
	print(*ans)


for _ in range(int(input())):
	_ = input()
	s = [1 if ch == '1' else 0 for ch in input()]
	balance = 0
	labels = [0] * len(s)
	stacks = [[], []]
	max_label = 0
	for (i, ch) in enumerate(s):
		if stacks[1 - ch]:
			j = stacks[1 - ch].pop()
			stacks[ch].append(i)
			labels[i] = labels[j]
		else:
			labels[i] = max_label + 1
			max_label += 1
			stacks[ch].append(i)
	print(max(labels))
	print(*labels)


from collections import defaultdict as ddict

def f():
	t = int(input())
	for _ in range(t):
		n = int(input())
		binstr = input()
		arr = [0] * n
		(ctr0, ctr1) = (0, 0)
		d = ddict(int)
		for i in range(n):
			if binstr[i] == '1':
				if ctr0 < i:
					ctr0 = i
				while ctr0 < n and binstr[ctr0] == '1':
					ctr0 += 1
				d[i] = ctr0
				if ctr0 < n:
					ctr0 += 1
			else:
				if ctr1 < i:
					ctr1 = i
				while ctr1 < n and binstr[ctr1] == '0':
					ctr1 += 1
				d[i] = ctr1
				if ctr1 < n:
					ctr1 += 1
		seqnum = 1
		ans = 0
		traversed = set()
		for i in range(n):
			if i in traversed:
				continue
			traversed.add(i)
			val = i
			while val < n:
				arr[val] = seqnum
				traversed.add(val)
				val = d[val]
			ans += 1
			seqnum += 1
		arr = list(map(lambda x: str(x), arr))
		arr = ' '.join(arr)
		print(ans)
		print(arr)
f()


from fractions import Fraction
from collections import defaultdict
import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	l = list(s)
	zero = []
	one = []
	cnt = 0
	a = []
	for i in range(n):
		a.append(0)
	for i in range(n):
		if l[i] == '0':
			if one == []:
				cnt += 1
				zero.append(cnt)
				a[i] = cnt
			else:
				var = one.pop()
				zero.append(var)
				a[i] = var
		elif zero == []:
			cnt += 1
			one.append(cnt)
			a[i] = cnt
		else:
			w = zero.pop()
			one.append(w)
			a[i] = w
	print(cnt)
	for i in a:
		print(i, end=' ')
	print()


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	ans = []
	one = deque()
	zero = deque()
	sq = 1
	if s[0] == '0':
		ans.append(1)
		one.append(1)
		for i in range(1, n):
			if s[i] == '0':
				if zero == deque([]):
					sq += 1
					ans.append(sq)
					one.append(sq)
				else:
					ans.append(zero[0])
					one.append(zero[0])
					zero.popleft()
			elif one == deque([]):
				sq += 1
				ans.append(sq)
				zero.append(sq)
			else:
				ans.append(one[0])
				zero.append(one[0])
				one.popleft()
	else:
		ans.append(1)
		zero.append(1)
		for i in range(1, n):
			if s[i] == '0':
				if zero == deque([]):
					sq += 1
					ans.append(sq)
					one.append(sq)
				else:
					ans.append(zero[0])
					one.append(zero[0])
					zero.popleft()
			elif one == deque([]):
				sq += 1
				ans.append(sq)
				zero.append(sq)
			else:
				ans.append(one[0])
				zero.append(one[0])
				one.popleft()
	print(len(set(ans)))
	for i in ans:
		print(i, end=' ')
	print()


from collections import Counter, deque

def func(s):
	hash = {0: deque(), 1: deque()}
	hash[1 - int(s[0])].append(1)
	res = [1]
	counter = 1
	for i in range(1, len(s)):
		n = int(s[i])
		if not hash[n]:
			counter += 1
			res.append(counter)
			hash[1 - n].append(counter)
		else:
			temp = hash[n].popleft()
			res.append(temp)
			hash[1 - n].append(temp)
	print(counter)
	return res
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	res = func(s)
	for i in res:
		print(i, end=' ')
	print()


def func(a, s):
	current = ''
	currIndex = 1
	prev0 = 0
	prev1 = 0
	prev0Index = []
	prev1Index = []
	res = []
	currmax = 1
	for i in range(a):
		if i == 0:
			currIndex = 1
			res = [1]
			if s[i] == '0':
				prev0 += 1
				prev0Index.append(currIndex)
			elif s[i] == '1':
				prev1 += 1
				prev1Index.append(currIndex)
		else:
			if s[i] == '0':
				if s[i - 1] == '1':
					if len(prev1Index) != 0:
						if res[-1] == prev1Index[-1]:
							prev1 -= 1
							prev1Index.pop()
					temp = res[-1]
					res.append(temp)
					prev0 += 1
					prev0Index.append(temp)
				elif prev1 != 0:
					prev1 -= 1
					temp = prev1Index.pop()
					res.append(temp)
					prev0 += 1
					prev0Index.append(temp)
				else:
					prev0 += 1
					temp = currmax + 1
					res.append(temp)
					prev0Index.append(temp)
			elif s[i] == '1':
				if s[i - 1] == '0':
					if len(prev0Index) != 0:
						if res[-1] == prev0Index[-1]:
							prev0 -= 1
							prev0Index.pop()
					temp = res[-1]
					res.append(temp)
					prev1 += 1
					prev1Index.append(temp)
				elif prev0 != 0:
					prev0 -= 1
					temp = prev0Index.pop()
					res.append(temp)
					prev1 += 1
					prev1Index.append(temp)
				else:
					prev1 += 1
					temp = currmax + 1
					res.append(temp)
					prev1Index.append(temp)
			if res[-1] > currmax:
				currmax = res[-1]
	print(currmax)
	print(*res)
t = int(input())
for _ in range(t):
	a = int(input())
	s = input()
	func(a, s)


for t in range(int(input())):
	x = int(input())
	s = list(input())
	n = 1
	result = ['1']
	end_1 = []
	end_0 = []
	if s[0] == '1':
		end_1.append('1')
	else:
		end_0.append('1')
	for i in range(1, x):
		if s[i] == '1':
			if len(end_0) == 0:
				result.append(str(n + 1))
				end_1.append(str(n + 1))
				n += 1
			else:
				result.append(end_0[0])
				end_1.append(end_0.pop(0))
		elif len(end_1) == 0:
			result.append(str(n + 1))
			end_0.append(str(n + 1))
			n += 1
		else:
			result.append(end_1[0])
			end_0.append(end_1.pop(0))
	print(n, ' '.join(result), sep='\n')


import heapq
from collections import Counter, defaultdict as dft

def mp():
	return map(int, input().split())

def ml():
	return list(map(int, input().split()))

def solve():
	n = int(input())
	s = input()
	h1 = []
	h0 = []
	res = [0] * n
	for i in range(n):
		if s[i] == '0':
			if len(h1) > 0:
				x = -heapq.heappop(h1)
				res[i] = x
				heapq.heappush(h0, -x)
			elif len(h0):
				res[i] = -h0[0] + 1
				heapq.heappush(h0, -res[i])
			else:
				heapq.heappush(h0, -1)
				res[i] = 1
		elif len(h0) > 0:
			x = -heapq.heappop(h0)
			res[i] = x
			heapq.heappush(h1, -x)
		elif len(h1):
			res[i] = -h1[0] + 1
			heapq.heappush(h1, -res[i])
		else:
			heapq.heappush(h1, -1)
			res[i] = 1
	print(max(res))
	print(*res)
t = int(input())
for _ in range(t):
	solve()


t = int(input())
cur = 0
zero = []
one = []
ans = []
for i in range(t):
	n = int(input())
	for i in input():
		if i == '1':
			if zero == []:
				cur += 1
				ans.append(cur)
				one.append(cur)
			else:
				ans.append(zero[0])
				one.append(zero[0])
				zero.pop(0)
		elif one == []:
			cur += 1
			ans.append(cur)
			zero.append(cur)
		else:
			ans.append(one[0])
			zero.append(one[0])
			one.pop(0)
	print(cur)
	print(*ans)
	cur = 0
	zero = []
	one = []
	ans = []


def check(A, seq):
	dict_a = dict()
	for i in range(len(seq)):
		if seq[i] not in dict_a.keys():
			dict_a[seq[i]] = A[i]
		elif A[i] == dict_a[seq[i]]:
			print(A, seq, dict_a[seq[i]])
			raise EOFError
		else:
			dict_a[seq[i]] = A[i]
T = int(input())
for t in range(T):
	N = input()
	A = input()
	state = A[0]
	unresolved = 0
	unresolved_state = A[0]
	sub_string = []
	sub_count = 0
	for a in A:
		if a == unresolved_state:
			unresolved += 1
			sub_string.append(unresolved)
		elif unresolved >= 1:
			sub_string.append(unresolved)
			unresolved -= 1
		else:
			unresolved = max(sub_string) + 1
			sub_string.append(unresolved)
			unresolved_state = a
	check(A, sub_string)
	print(max(sub_string))
	print(' '.join(list(map(str, sub_string))))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input()))
	l1 = [[], []]
	l1[abs(l[0] - 1)].append(1)
	(r, a) = ([1], 1)
	for i in l[1:]:
		if l1[i]:
			b = l1[i].pop()
			r.append(b)
			l1[abs(i - 1)].append(b)
		else:
			a += 1
			r.append(a)
			l1[abs(i - 1)].append(a)
	print(a)
	print(*r)


n = int(input())
for i in range(0, n):
	l = int(input())
	seq = list(map(int, list(input())))
	seq0 = []
	seq1 = []
	ans = [0] * l
	for i in range(0, l):
		pos = len(seq0) + len(seq1)
		if seq[i] == 0:
			if len(seq1) == 0:
				seq0.append(pos)
			else:
				pos = seq1.pop()
				seq0.append(pos)
		elif len(seq0) == 0:
			seq1.append(pos)
		else:
			pos = seq0.pop()
			seq1.append(pos)
		ans[i] = pos
	print(len(seq0) + len(seq1))
	[print(i + 1, end=' ') for i in ans]
	print()


import math
from collections import deque
from sys import stdin, stdout
from string import ascii_letters
input = stdin.readline
letters = ascii_letters[:26]
for _ in range(int(input())):
	n = int(input())
	text = list(input().strip())
	res = []
	zeros = []
	ones = []
	last = 0
	for i in text:
		if i == '0':
			if len(ones):
				res.append(ones[-1])
				zeros.append(ones[-1])
				ones.pop(-1)
			else:
				last += 1
				zeros.append(last)
				res.append(zeros[-1])
		elif len(zeros):
			res.append(zeros[-1])
			ones.append(zeros[-1])
			zeros.pop(-1)
		else:
			last += 1
			ones.append(last)
			res.append(ones[-1])
	print(last)
	print(*res)


test = int(input())
for _ in range(test):
	n = int(input())
	s = input()
	(ans, ones, zeroes) = ([], [], [])
	(len1, len2) = (-1, -1)
	subs = 0
	for i in range(n):
		if s[i] == '1':
			if len1 == -1:
				subs = subs + 1
				ans.append(subs)
				zeroes.append(subs)
				len2 = len2 + 1
			else:
				ans.append(ones[len1])
				zeroes.append(ones[len1])
				ones.pop()
				len1 = len1 - 1
				len2 = len2 + 1
		elif len2 == -1:
			subs = subs + 1
			ans.append(subs)
			ones.append(subs)
			len1 = len1 + 1
		else:
			ans.append(zeroes[len2])
			ones.append(zeroes[len2])
			zeroes.pop()
			len2 = len2 - 1
			len1 = len1 + 1
	print(subs)
	for each in ans:
		print(each, end=' ')
	print()


from collections import defaultdict

def neg(c):
	if c == '1':
		return '0'
	return '1'

def d(s):
	if len(s) == 1:
		print('1\n1')
		return
	seq_ctr = 1
	m = defaultdict(set)
	m[neg(s[0])].add(1)
	affils = [seq_ctr]
	for i in range(1, len(s)):
		if len(m[s[i]]) > 0:
			other = neg(s[i])
			removed = m[s[i]].pop()
			m[other].add(removed)
			affils.append(removed)
		else:
			seq_ctr += 1
			m[neg(s[i])].add(seq_ctr)
			affils.append(seq_ctr)
	print(seq_ctr)
	print(' '.join([str(e) for e in affils]))
for i in range(int(input())):
	input()
	d(input())


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	s = input().rstrip() + '$'
	group = 1
	ans = []
	zeros_room = []
	ones_room = []
	for (ch1, ch2) in zip(s, s[1:]):
		if ch1 == '1' and ch2 == '1':
			if ones_room:
				index = ones_room.pop()
				ans.append(index)
				zeros_room.append(index)
			else:
				ans.append(group)
				zeros_room.append(group)
				group += 1
		elif ch1 == '0' and ch2 == '0':
			if zeros_room:
				index = zeros_room.pop()
				ans.append(index)
				ones_room.append(index)
			else:
				ans.append(group)
				ones_room.append(group)
				group += 1
		else:
			ans.append(group)
	print(group)
	print(*ans)


a = int(input())
for i in range(a):
	s = input()
	s = input()
	ans = [1]
	last = [s[0]]
	one = []
	zero = []
	if s[0] == '1':
		zero.append(1)
	else:
		one.append(1)
	cnt = 1
	for i in range(1, len(s)):
		if s[i] == '1':
			if len(one) == 0 and len(zero) == 0:
				ans.append(cnt)
				zero.append(cnt)
			elif len(one) != 0:
				m = one.pop()
				ans.append(m)
				zero.append(m)
			else:
				cnt += 1
				ans.append(cnt)
				zero.append(cnt)
		elif len(one) == 0 and len(zero) == 0:
			ans.append(cnt)
			one.append(cnt)
		elif len(zero) != 0:
			m = zero.pop()
			ans.append(m)
			one.append(m)
		else:
			cnt += 1
			ans.append(cnt)
			one.append(cnt)
	print(cnt)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	zero_end = []
	one_end = []
	indices = []
	counter = 0
	for i in s:
		if i == '0':
			if len(one_end) == 0:
				counter += 1
				zero_end.append(counter)
				indices.append(counter)
			else:
				num = one_end.pop()
				zero_end.append(num)
				indices.append(num)
		elif len(zero_end) == 0:
			counter += 1
			one_end.append(counter)
			indices.append(counter)
		else:
			num = zero_end.pop()
			one_end.append(num)
			indices.append(num)
	print(counter)
	print(*indices)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, list(input())))
	ans = 0
	zz = set({})
	oo = set({})
	li = []
	for i in range(n):
		if ar[i] == 0:
			if oo:
				for j in oo:
					li.append(j)
					break
				oo.remove(j)
				zz.add(j)
			else:
				ans += 1
				li.append(ans)
				zz.add(ans)
		elif zz:
			for j in zz:
				li.append(j)
				break
			zz.remove(j)
			oo.add(j)
		else:
			ans += 1
			li.append(ans)
			oo.add(ans)
	print(ans)
	print(*li)


T = int(input())
for _ in range(T):
	N = int(input())
	S = input()
	cnt = {'0': [], '1': []}
	l = 0
	stock = ['']
	now = 0
	now_max = 0
	prev = '2'
	ans = []
	for i in range(N):
		if S[i] == prev:
			cnt[prev].append(now)
			if prev == '0':
				if cnt['1']:
					now = cnt['1'].pop()
					stock[now] += prev
				else:
					now = len(stock)
					stock.append(S[i])
			elif cnt['0']:
				now = cnt['0'].pop()
				stock[now] += prev
			else:
				now = len(stock)
				stock.append(S[i])
		else:
			stock[now] += S[i]
		prev = S[i]
		ans.append(now + 1)
	print(len(stock))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	d = [0] * (n + 1)
	for i in range(n):
		d[i + 1] = d[i] + (1 if s[i] == '1' else -1)
	for i in range(n):
		if s[i] == '0':
			d[i] -= 1
	md = min(d)
	for i in range(n):
		d[i] -= md - 1
	d.pop(n)
	print(max(d))
	print(*d)


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	ans = [-1] * n
	end0 = []
	end1 = []
	maxa = 0
	maxend0 = 0
	maxend1 = 0
	for i in range(n):
		if a[i] == '0':
			if len(end1) != 0:
				ans[i] = end1[-1]
				end0.append(ans[i])
				maxend0 += 1
				end1.pop()
				maxend1 -= 1
			elif len(end0) != 0:
				end0.append(maxend0 + 1)
				ans[i] = end0[-1]
				maxend0 += 1
			else:
				end0.append(1)
				maxend0 = 1
				ans[i] = 1
		elif len(end0) != 0:
			ans[i] = end0[-1]
			end1.append(ans[i])
			maxend1 += 1
			end0.pop()
			maxend0 -= 1
		elif len(end1) != 0:
			end1.append(maxend1 + 1)
			ans[i] = end1[-1]
			maxend1 += 1
		else:
			end1.append(1)
			ans[i] = 1
			maxend1 = 1
	print(max(ans))
	print(*ans)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def solve():
	n = inp()
	s = insr()
	ans = 0
	count = [-1 for i in range(n)]
	subs = [[], []]
	for i in range(n):
		x = int(int(s[i]) - 0)
		if len(subs[x]) == 0:
			count[i] = ans
			ans += 1
		else:
			count[i] = subs[x][-1]
			subs[x].pop(-1)
		subs[not x].append(count[i])
	print(ans)
	for i in range(len(count)):
		print(count[i] + 1, end=' ')
	print()
t = inp()
while t > 0:
	solve()
	t -= 1


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdarr = lambda : map(int, stdstr().split())
mod = 1000000007
for _ in range(stdint()):
	n = stdint()
	s = input()
	stack = []
	sub = 0
	res = [0] * n
	freq = Counter(s)
	last = {'0': [], '1': []}
	for i in range(n):
		opp = str(int(s[i]) ^ 1)
		if len(last[opp]) == 0:
			last[s[i]].append([(s[i], i)])
		else:
			l = last[opp][-1]
			l.append((s[i], i))
			del last[opp][-1]
			last[s[i]].append(l)
	for i in ['0', '1']:
		for j in last[i]:
			sub += 1
			for k in j:
				res[k[1]] = sub
	print(sub)
	print(*res)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	res = [0 for _ in range(n)]
	zero = []
	one = []
	for i in range(n):
		p = len(zero) + len(one)
		if s[i] == '0':
			if len(one) == 0:
				zero.append(p)
			else:
				p = one.pop()
				zero.append(p)
		elif len(zero) == 0:
			one.append(p)
		else:
			p = zero.pop()
			one.append(p)
		res[i] = p
	print(len(zero) + len(one))
	for j in range(n):
		if j != n - 1:
			print(res[j] + 1, end=' ')
		else:
			print(res[j] + 1)


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	val = {}
	(zero, one, mx) = ([], [], 0)
	for i in range(n):
		if s[i] == '0':
			if len(one) == 0:
				mx += 1
				val[mx] = [i]
				zero.append(mx)
			else:
				seq = one.pop()
				val[seq].append(i)
				zero.append(seq)
		elif len(zero) == 0:
			mx += 1
			val[mx] = [i]
			one.append(mx)
		else:
			seq = zero.pop()
			val[seq].append(i)
			one.append(seq)
	res = [_ for i in range(n)]
	for i in val.keys():
		for j in val[i]:
			res[j] = i
	print(mx)
	for i in res:
		print(i, end=' ')
	print()


import os
import heapq
import sys, threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10 ** 5)
from io import BytesIO, IOBase

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def power(x, p, m):
	res = 1
	while p:
		if p & 1:
			res = res * x % m
		x = x * x % m
		p >>= 1
	return res

def inar():
	return [int(k) for k in input().split()]

def lcm(num1, num2):
	return num1 * num2 // gcd(num1, num2)

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		st = input()
		res = []
		ans = 1
		dic = defaultdict(set)
		count = 1
		for i in range(n - 1):
			if st[i] == st[i + 1]:
				dic[st[i]].add(count)
				res.append(count)
				if st[i + 1] == '0':
					temp = '1'
				else:
					temp = '0'
				if temp in dic:
					take = -1
					for el in dic[temp]:
						take = el
						break
					dic[temp].remove(take)
					if len(dic[temp]) == 0:
						del dic[temp]
					count = take
				else:
					ans += 1
					count = ans
			else:
				res.append(count)
		res.append(count)
		print(ans)
		print(*res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_str():
	return input().decode().strip()

def rint():
	return map(int, input().split())

def oint():
	return int(input())
t = oint()
for _ in range(t):
	n = oint()
	b = get_str()
	ans = [0] * n
	maxg = 0
	z = []
	o = []
	for (i, bb) in enumerate(b):
		if bb == '1':
			if not z:
				maxg += 1
				ans[i] = maxg
				o.append(maxg)
			else:
				ans[i] = z.pop()
				o.append(ans[i])
		if bb == '0':
			if not o:
				maxg += 1
				ans[i] = maxg
				z.append(maxg)
			else:
				ans[i] = o.pop()
				z.append(ans[i])
	print(maxg)
	print(*ans)


from sys import stdin
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
from collections import deque
(t,) = gil()
for _ in range(t):
	(n,) = gil()
	a = gbs()
	rqd = {a[0]: [[0]], a[0] ^ 1: []}
	for i in range(1, n):
		if len(rqd[a[i] ^ 1]):
			lst = rqd[a[i] ^ 1].pop()
			lst.append(i)
			rqd[a[i]].append(lst)
		else:
			rqd[a[i]].append([i])
	k = len(rqd[0]) + len(rqd[1])
	print(k)
	ans = [0] * n
	for i in range(1, k + 1):
		if len(rqd[0]):
			for idx in rqd[0].pop():
				ans[idx] = i
		elif len(rqd[1]):
			for idx in rqd[1].pop():
				ans[idx] = i
	for a in ans:
		print(a, end=' ')
	print()


import collections

def solve(lst):
	stck = []
	lst = [int(i) for i in lst]
	prev = -1
	(mx1, mx2) = (1, 1)
	mps = {0: [], 1: []}
	for i in range(len(lst)):
		if lst[i]:
			if mps[lst[i] - 1]:
				p = mps[lst[i] - 1].pop()
				mps[lst[i]].append(p)
				stck.append(p)
				if mx1 < p:
					mx1 = p
			elif mps[lst[i]]:
				mx1 += 1
				stck.append(mx1)
				mps[lst[i]].append(mx1)
			else:
				mps[lst[i]].append(mx1)
				stck.append(mx1)
		elif mps[lst[i] + 1]:
			p = mps[lst[i] + 1].pop()
			mps[lst[i]].append(p)
			stck.append(p)
			if mx2 < p:
				mx2 = p
		elif mps[lst[i]]:
			mx2 += 1
			stck.append(mx2)
			mps[lst[i]].append(mx2)
		else:
			mps[lst[i]].append(mx2)
			stck.append(mx2)
	return stck

def sort(key):
	return key[0]
ans = []
n = int(input())
for i in range(n):
	k = int(input())
	lst = input()
	k = [str(i) for i in solve(lst)]
	print(max(solve(lst)))
	print(' '.join(k))
for i in ans:
	print(i)


T = int(input())
for _ in range(0, T):
	n = int(input())
	s = input()
	c0 = 0
	c1 = 0
	ans = []
	C0 = []
	C1 = []
	tot = 0
	for i in range(0, len(s)):
		if s[i] == '0':
			if c1 > 0:
				c1 -= 1
				c0 += 1
				ele = C1.pop()
				C0.append(ele)
				ans.append(ele)
			else:
				c0 += 1
				tot += 1
				C0.append(tot)
				ans.append(tot)
		elif c0 > 0:
			c0 -= 1
			c1 += 1
			ele = C0.pop()
			C1.append(ele)
			ans.append(ele)
		else:
			c1 += 1
			tot += 1
			C1.append(tot)
			ans.append(tot)
	print(tot)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(input())
	res = [0] * n
	q1 = []
	q0 = []
	count = 1
	res[0] = count
	if arr[0] == '0':
		q0.append(count)
	else:
		q1.append(count)
	for i in range(1, n):
		if arr[i] == '0':
			if len(q1) == 0:
				count += 1
				res[i] = count
				q0.append(count)
			else:
				res[i] = q1[-1]
				q0.append(q1[-1])
				q1.pop(-1)
		if arr[i] == '1':
			if len(q0) == 0:
				count += 1
				res[i] = count
				q1.append(count)
			else:
				res[i] = q0[-1]
				q1.append(q0[-1])
				q0.pop(-1)
	print(count)
	print(*res)


def read_nums():
	return [int(x) for x in input().split()]

def solve():
	_ = read_nums()
	s = input()
	(zeros, ones) = ([], [])
	res = []
	for ch in s:
		if ch == '1':
			if len(zeros) == 0:
				ones.append(len(zeros) + len(ones) + 1)
				res.append(len(zeros) + len(ones))
			else:
				index = zeros.pop()
				res.append(index)
				ones.append(index)
		elif len(ones) == 0:
			zeros.append(len(zeros) + len(ones) + 1)
			res.append(len(zeros) + len(ones))
		else:
			index = ones.pop()
			res.append(index)
			zeros.append(index)
	print(max(res))
	print(' '.join(map(str, res)))

def main():
	(t,) = read_nums()
	for _ in range(t):
		solve()
main()


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = 0
	ec = 0
	oc = 0
	l = []
	e = []
	o = []
	c = 0
	for i in s:
		if i == '0':
			if oc == 0:
				ans += 1
				ec += 1
				c += 1
				e.append(c)
				l.append(c)
			else:
				oc -= 1
				ec += 1
				temp = o.pop()
				e.append(temp)
				l.append(temp)
		elif ec == 0:
			oc += 1
			ans += 1
			c += 1
			o.append(c)
			l.append(c)
		else:
			oc += 1
			ec -= 1
			temp = e.pop()
			o.append(temp)
			l.append(temp)
	print(ans)
	for i in l:
		print(i, end=' ')
	print()


T = int(input())
for _ in range(T):
	n = int(input())
	s = input()
	ans1 = 0
	s_0 = []
	s_1 = []
	ans = []
	for i in range(n):
		if s[i] == '0':
			if len(s_1) == 0:
				ans1 += 1
				s_0.append(ans1)
				prev_ans1 = ans1
			else:
				prev_ans1 = s_1.pop()
				s_0.append(prev_ans1)
		elif len(s_0) == 0:
			ans1 += 1
			s_1.append(ans1)
			prev_ans1 = ans1
		else:
			prev_ans1 = s_0.pop()
			s_1.append(prev_ans1)
		ans.append(prev_ans1)
	print(ans1)
	print(*ans)


rr = lambda : input()
rri = lambda : int(input())
rrm = lambda : list(map(int, input().split()))
INF = float('inf')

def solve(N, S):
	ans = []
	zero = []
	one = []
	i = 1
	for c in S:
		if c == '0':
			if one:
				o = one.pop()
				zero.append(o)
				ans.append(str(o))
			else:
				zero.append(i)
				ans.append(str(i))
				i += 1
		elif c == '1':
			if zero:
				z = zero.pop()
				one.append(z)
				ans.append(str(z))
			else:
				one.append(i)
				ans.append(str(i))
				i += 1
	subseq = len(zero) + len(one)
	print(subseq)
	print(' '.join(ans))
t = rri()
for _ in range(t):
	N = rri()
	S = rr()
	solve(N, S)


import math
import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlst():
	return list(map(int, input().split()))

def instr():
	s = input()
	return list(s[:len(s) - 1])

def invar():
	return map(int, input().split())

def pbd(n, s):
	s0 = []
	s1 = []
	res = []
	id = 0
	for i in range(n):
		if s[i] == '0':
			if len(s1) == 0:
				id += 1
				s0.append(id)
				res.append(id)
			else:
				s0.append(s1[-1])
				res.append(s1[-1])
				s1.pop()
		elif s[i] == '1':
			if len(s0) == 0:
				id += 1
				s1.append(id)
				res.append(id)
			else:
				s1.append(s0[-1])
				res.append(s0[-1])
				s0.pop()
	print(id)
	print(*res)
for _ in range(inp()):
	n = inp()
	s = input()
	pbd(n, s)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	s0 = []
	s1 = []
	ans = []
	for i in range(n):
		sub = len(s0) + len(s1) + 1
		if s[i] == '0':
			if s1:
				sub = s1.pop()
				s0.append(sub)
			else:
				s0.append(sub)
		elif s0:
			sub = s0.pop()
			s1.append(sub)
		else:
			s1.append(sub)
		ans.append(sub)
	print(len(s0) + len(s1))
	print(' '.join((str(x) for x in ans)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input()))
	b = []
	m = 0
	e0 = []
	e1 = []
	for i in a:
		if i == 0:
			if e1 != []:
				x = e1.pop()
				e0.append(x)
				b.append(x)
			else:
				m += 1
				e0.append(m)
				b.append(m)
		elif e0 != []:
			x = e0.pop()
			e1.append(x)
			b.append(x)
		else:
			m += 1
			e1.append(m)
			b.append(m)
	print(m)
	print(*b)


import sys, os, io
import math, bisect, operator
(inf, mod) = (float('inf'), 10 ** 9 + 7)
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int, input().split()))
(test,) = Neo()
for i in range(test):
	(n,) = Neo()
	s = input()
	c = 1
	one = set()
	zero = set()
	Ans = [1]
	for i in range(1, len(s)):
		if s[i] != s[i - 1]:
			Ans.append(c)
		elif s[i - 1] == '1':
			if zero:
				t = zero.pop()
				one.add(t)
				Ans.append(t)
			else:
				one.add(c)
				c += 1
				Ans.append(c)
		elif one:
			t = one.pop()
			zero.add(t)
			Ans.append(t)
		else:
			zero.add(c)
			c += 1
			Ans.append(c)
	print(len(set(Ans)))
	print(*Ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	totalNoOfSubsequence = 0
	endingWith0 = []
	endingWith1 = []
	ans = []
	for c in s:
		if int(c) == 0:
			if len(endingWith1) > 0:
				seqNo = endingWith1.pop()
				ans.append(seqNo)
				endingWith0.append(seqNo)
			else:
				seqNo = totalNoOfSubsequence + 1
				totalNoOfSubsequence += 1
				endingWith0.append(seqNo)
				ans.append(seqNo)
		elif len(endingWith0) > 0:
			seqNo = endingWith0.pop()
			ans.append(seqNo)
			endingWith1.append(seqNo)
		else:
			seqNo = totalNoOfSubsequence + 1
			totalNoOfSubsequence += 1
			endingWith1.append(seqNo)
			ans.append(seqNo)
	print(totalNoOfSubsequence)
	print(' '.join(map(str, ans)))


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	sub_no = []
	last_one = deque()
	last_zero = deque()
	for char in s:
		if char == '0':
			if len(last_one) == 0:
				new_sub = len(last_one) + len(last_zero) + 1
				last_zero.append(new_sub)
				sub_no.append(new_sub)
			else:
				sub = last_one.popleft()
				sub_no.append(sub)
				last_zero.append(sub)
		elif len(last_zero) == 0:
			new_sub = len(last_one) + len(last_zero) + 1
			last_one.append(new_sub)
			sub_no.append(new_sub)
		else:
			sub = last_zero.popleft()
			sub_no.append(sub)
			last_one.append(sub)
	print(len(last_one) + len(last_zero))
	for i in sub_no:
		print(i, end=' ')
	print()


for t in range(int(input())):
	n = int(input())
	s = input()
	dp = [1] * n
	start = s[0]
	cnt = 1
	for i in range(n):
		if s[i] == start:
			dp[i] = cnt
			cnt += 1
		else:
			dp[i] = cnt - 1
			cnt -= 1
	mini = min(dp)
	if mini <= 0:
		for i in range(n):
			dp[i] = dp[i] + 1 + abs(mini)
	ans = max(dp)
	print(ans)
	print(*dp)


t = int(input())
for tc in range(t):
	n = int(input())
	s = input()
	ones = []
	zeros = []
	pos = []
	posnew = 0
	for ch in s:
		posnew = len(ones) + len(zeros)
		if ch == '0':
			if len(ones) == 0:
				zeros.append(posnew)
			else:
				posnew = ones.pop()
				zeros.append(posnew)
		elif len(zeros) == 0:
			ones.append(posnew)
		else:
			posnew = zeros.pop()
			ones.append(posnew)
		pos.append(posnew + 1)
	print(max(pos))
	print(*pos)


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, list(input())))
	dp = [1] * len(s)
	ending = [[], []]
	m = 1
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			ending[s[i - 1]].append(i - 1)
			if ending[(s[i] + 1) % 2]:
				dp[i] = dp[ending[(s[i] + 1) % 2].pop()]
			else:
				m += 1
				dp[i] = m
		else:
			dp[i] = dp[i - 1]
	print(m)
	print(*dp)


t = int(input().split()[0])
for case in range(t):
	n = int(input().split()[0])
	s = input().split()[0]
	zeros = set()
	ones = set()
	ans = 0
	arr = []
	for i in range(n):
		if s[i] == '0':
			if len(zeros) == 0:
				ans += 1
				ones.add(ans)
				arr.append(ans)
			else:
				curr = zeros.pop()
				ones.add(curr)
				arr.append(curr)
		if s[i] == '1':
			if len(ones) == 0:
				ans += 1
				zeros.add(ans)
				arr.append(ans)
			else:
				curr = ones.pop()
				zeros.add(curr)
				arr.append(curr)
	print(ans)
	print(*arr)


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	zero = deque()
	ones = deque()
	ans = 0
	l = []
	for i in s:
		if i == '0':
			if len(ones) == 0:
				ans += 1
				zero.append(ans)
				l.append(ans)
			else:
				x = ones.pop()
				zero.append(x)
				l.append(x)
		elif len(zero) == 0:
			ans += 1
			ones.append(ans)
			l.append(ans)
		else:
			x = zero.pop()
			ones.append(x)
			l.append(x)
	print(ans)
	print(' '.join((str(i) for i in l)))


import sys, math
mod = 10 ** 9

def solve(test_index):
	n = int(input())
	s = input()
	(a, b) = ([], [])
	p = 0
	ans = []
	for c in s:
		if c == '0':
			if len(a) == 0:
				p += 1
				ans.append(p)
				b.append(p)
			else:
				seq = a.pop()
				ans.append(seq)
				b.append(seq)
		elif len(b) == 0:
			p += 1
			ans.append(p)
			a.append(p)
		else:
			seq = b.pop()
			ans.append(seq)
			a.append(seq)
	print(p)
	print(*ans)
	return
if 'PyPy' not in sys.version:
	sys.stdin = open('input.txt', 'r')
sys.setrecursionlimit(100000)
num_tests = 1
num_tests = int(input())
for test in range(1, num_tests + 1):
	solve(test)


from sys import stdin, stdout
from collections import deque

def main():
	t = int(stdin.readline())
	for case in range(t):
		n = int(stdin.readline())
		s = stdin.readline()
		nseq = 0
		label = [0] * n
		qz = deque()
		qo = deque()
		for idx in range(n):
			if s[idx] == '0':
				if qo:
					jdx = qo.pop()
					label[idx] = label[jdx]
				else:
					nseq += 1
					label[idx] = nseq
				qz.append(idx)
			else:
				if qz:
					jdx = qz.pop()
					label[idx] = label[jdx]
				else:
					nseq += 1
					label[idx] = nseq
				qo.append(idx)
		stdout.write(str(max(label)))
		stdout.write('\n')
		stdout.write(' '.join(map(str, label)))
		stdout.write('\n')
	return
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
import bisect as bs
from collections import deque as dq
for _ in range(N()):
	n = N()
	s = input()
	res = [1]
	o = dq()
	z = dq()
	if s[0] == '1':
		o.append(1)
	else:
		z.append(1)
	for c in s[1:]:
		if c == '1':
			if not z:
				tmp = o[-1] + 1
				o.append(tmp)
			else:
				tmp = z.popleft()
				bs.insort_left(o, tmp)
		elif not o:
			tmp = z[-1] + 1
			z.append(tmp)
		else:
			tmp = o.popleft()
			bs.insort_left(z, tmp)
		res.append(tmp)
	if not o:
		print(z[-1])
	elif not z:
		print(o[-1])
	else:
		print(max(o[-1], z[-1]))
	print_list(res)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	b = []
	for j in s:
		b.append(int(j))
	res = [0] * n
	zero = 0
	one = 0
	pro = []
	prz = []
	j = 0
	k = 0
	while j < n:
		if b[j] == 0:
			if pro == []:
				k += 1
				res[j] = k
			else:
				res[j] = pro.pop()
			prz.append(res[j])
		else:
			if prz == []:
				k += 1
				res[j] = k
			else:
				res[j] = prz.pop()
			pro.append(res[j])
		j += 1
	print(len(set(res)))
	print(*res)


t = int(input())
for _ in range(t):
	n = int(input())
	st = input()
	dd = {0: [], 1: []}
	x = 0
	(c1, c0) = (0, 0)
	li = [0] * n
	for i in range(n):
		s = st[i]
		if s == '1':
			if c0 > 0:
				c0 -= 1
				c1 += 1
				y = dd[0].pop()
				dd[1].append(y)
				li[i] = y
			else:
				c1 += 1
				x += 1
				dd[1].append(x)
				li[i] = x
		elif c1 > 0:
			c1 -= 1
			c0 += 1
			y = dd[1].pop()
			dd[0].append(y)
			li[i] = y
		else:
			c0 += 1
			x += 1
			dd[0].append(x)
			li[i] = x
	print(x)
	print(*li)


from collections import deque

def solve(n, ar):
	q1 = deque()
	q2 = deque()
	ans = [0] * n
	cnt = 0
	for i in range(n):
		if ar[i] == '0':
			if not q1:
				cnt += 1
				ans[i] = cnt
				q2.append(cnt)
			else:
				p = q1.popleft()
				ans[i] = p
				q2.append(p)
		elif not q2:
			cnt += 1
			ans[i] = cnt
			q1.append(cnt)
		else:
			p = q2.popleft()
			ans[i] = p
			q1.append(p)
	print(cnt)
	print(' '.join(map(str, ans)))
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(input())
	solve(n, ar)


ones = [0 for i in range(2 * 10 ** 5 + 1)]
zeros = [0 for i in range(2 * 10 ** 5 + 1)]
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input()]
	d = [0 for i in range(n)]
	o = -1
	z = -1
	c = 1
	for i in range(n):
		if a[i] == 0:
			if o == -1:
				z += 1
				zeros[z] = c
				d[i] = c
				c += 1
			else:
				k = ones[o]
				d[i] = k
				o -= 1
				z += 1
				zeros[z] = k
		elif z == -1:
			o += 1
			ones[o] = c
			d[i] = c
			c += 1
		else:
			k = zeros[z]
			d[i] = k
			z -= 1
			o += 1
			ones[o] = k
	print(c - 1)
	print(*d)


from sys import stdin, stdout
test = int(stdin.readline())
for _ in range(test):
	n = int(stdin.readline())
	s = [int(x) for x in list(stdin.readline().strip())]
	if s.count(1) == 0 or s.count(0) == 0:
		ans = [i + 1 for i in range(n)]
		print(n)
		print(*ans)
		continue
	ans = [0 for i in range(n)]
	ans[0] = 1
	last = [[], []]
	cn = 1
	for i in range(1, n):
		if s[i] == s[i - 1]:
			if last[not s[i]] == []:
				ans[i] = cn + 1
				cn += 1
			else:
				ans[i] = last[not s[i]][-1]
				last[not s[i]].pop()
			last[s[i]].append(ans[i])
		else:
			ans[i] = 1
	print(cn)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	subCount = 0
	i = 0
	a0 = []
	a1 = []
	ans = []
	while i < n:
		if subCount == 0:
			run = True
			while i < n and run:
				if i + 1 < n and s[i] == s[i + 1]:
					if s[i] == '0':
						a0.append(0)
					else:
						a1.append(0)
					run = False
				ans.append(1)
				i += 1
			subCount += 1
		else:
			found = False
			idx = 0
			if s[i] == '0':
				if len(a1):
					idx = a1.pop()
					found = True
			elif len(a0):
				idx = a0.pop()
				found = True
			if not found:
				ln = subCount
				run = True
				while i < n and run:
					if i + 1 < n and s[i] == s[i + 1]:
						if s[i] == '0':
							a0.append(ln)
						else:
							a1.append(ln)
						run = False
					ans.append(ln + 1)
					i += 1
				subCount += 1
			else:
				ln = subCount
				run = True
				while i < n and run:
					if i + 1 < n and s[i] == s[i + 1]:
						if s[i] == '0':
							a0.append(idx)
						else:
							a1.append(idx)
						run = False
					ans.append(idx + 1)
					i += 1
	print(subCount)
	print(*ans)


for t in range(int(input())):
	n = int(input())
	s = input()
	d = [0] * n
	k = 0
	p0 = []
	p1 = []
	for i in range(n):
		if s[i] == '0':
			if len(p1) == 0:
				k += 1
				p = k
			else:
				p = p1.pop()
			p0.append(p)
		else:
			if len(p0) == 0:
				k += 1
				p = k
			else:
				p = p0.pop()
			p1.append(p)
		d[i] = p
	print(k)
	print(*d)


t = int(input())
for gg in range(t):
	ans = 1
	a = [1]
	k1 = []
	k0 = []
	n = int(input())
	s = input()
	lst = s[0]
	if s[0] == '1':
		k1.append(1)
	else:
		k0.append(1)
	for i in range(1, n):
		if s[i] == '1':
			if len(k0) != 0:
				cur = k0.pop()
				k1.append(cur)
				a.append(cur)
			else:
				ans += 1
				k1.append(ans)
				a.append(ans)
			lst = '1'
		else:
			if len(k1) != 0:
				cur = k1.pop()
				k0.append(cur)
				a.append(cur)
			else:
				ans += 1
				k0.append(ans)
				a.append(ans)
			lst = '0'
	print(ans)
	print(*a)


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	(mzero, mone) = (0, 0)
	ans = []
	(zero, one) = (deque([]), deque([]))
	for i in s:
		if i == '0':
			if len(one) == 0:
				mone += 1
				ans.append(mone)
				zero.append(mone)
			else:
				x = one.popleft()
				ans.append(x)
				zero.append(x)
				mone = max(x, mone)
		elif len(zero) == 0:
			mzero += 1
			ans.append(mzero)
			one.append(mzero)
		else:
			x = zero.popleft()
			ans.append(x)
			one.append(x)
			mzero = max(x, mzero)
	print(len(set(ans)))
	for i in ans:
		print(i, end=' ')
	print()


import re

def binary(a):
	(at_one, at_zero) = ([], [])
	val = 0
	ans = [0] * len(a)
	for i in range(len(a)):
		if a[i] == '0' and at_one:
			ans[i] = at_one.pop()
			at_zero.append(ans[i])
		elif a[i] == '0':
			val += 1
			ans[i] = val
			at_zero.append(val)
		elif a[i] == '1' and at_zero:
			ans[i] = at_zero.pop()
			at_one.append(ans[i])
		elif a[i] == '1':
			val += 1
			ans[i] = val
			at_one.append(val)
	ans.insert(0, max(ans))
	return ans
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = input()
	ans.append(binary(a))
for i in ans:
	print(i[0])
	print(*i[1:])


for _ in range(int(input())):
	n = int(input())
	s = input()
	pos = [0 for i in range(n)]
	num0 = 0
	num1 = 0
	ans = 0
	for i in range(n):
		if s[i] == '0':
			pos[i] = num0 + 1
			num0 += 1
			if num1 > 0:
				num1 -= 1
			else:
				ans += 1
		else:
			num1 += 1
			if num0 > 0:
				pos[i] = num0
				num0 -= 1
			else:
				pos[i] = ans + 1
				ans += 1
	print(ans)
	print(*pos)


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	n = iinput()
	s = input()
	ones = deque()
	zeros = deque()
	mxval = 1
	if s[0] == '1':
		zeros.append(1)
	else:
		ones.append(1)
	ans = [0] * n
	for i in range(n):
		if s[i] == '1':
			if zeros:
				val = zeros.pop()
				ans[i] = val
				ones.append(val)
			else:
				mxval += 1
				ans[i] = mxval
				ones.append(mxval)
		elif ones:
			val = ones.pop()
			ans[i] = val
			zeros.append(val)
		else:
			mxval += 1
			ans[i] = mxval
			zeros.append(mxval)
	print(max(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	s = str(input())
	a_zero = []
	a_one = []
	if s[0] == '0':
		a_zero.append(1)
	elif s[0] == '1':
		a_one.append(1)
	check = [0 for i in range(n)]
	check[0] = 1
	group_cnt = 1
	for i in range(1, n):
		if s[i] == '0':
			if len(a_one) > 0:
				last = a_one.pop()
				a_zero.append(last)
				check[i] = last
			else:
				group_cnt += 1
				a_zero.append(group_cnt)
				check[i] = group_cnt
		elif s[i] == '1':
			if len(a_zero) > 0:
				last = a_zero.pop()
				a_one.append(last)
				check[i] = last
			else:
				group_cnt += 1
				a_one.append(group_cnt)
				check[i] = group_cnt
	print(group_cnt)
	print(' '.join(map(str, check)))


for _ in range(int(input())):
	c = 0
	one = []
	zero = []
	n = int(input())
	string = input()
	output = []
	for i in string:
		if i == '0':
			if len(one) == 0:
				c += 1
				zero.append(c)
				output.append(c)
			else:
				x = one.pop()
				zero.append(x)
				output.append(x)
		if i == '1':
			if len(zero) == 0:
				c += 1
				one.append(c)
				output.append(c)
			else:
				x = zero.pop()
				one.append(x)
				output.append(x)
	print(c)
	for i in output:
		print(i, end=' ')
	print()


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input().strip()
	zerostack = deque()
	onestack = deque()
	subs = 0
	subind = []
	for i in range(n):
		if s[i] == '0':
			if onestack:
				temp = onestack.pop()
				subind.append(temp)
				zerostack.append(temp)
			else:
				subs += 1
				subind.append(subs)
				zerostack.append(subs)
		elif zerostack:
			temp = zerostack.pop()
			subind.append(temp)
			onestack.append(temp)
		else:
			subs += 1
			subind.append(subs)
			onestack.append(subs)
	print(max(subind))
	print(' '.join([str(x) for x in subind]))


for i in range(int(input())):
	n = int(input())
	a = list(input())
	d = 0
	ans = []
	for i in range(n):
		if a[i] == '0':
			d += 1
			ans.append(d)
		else:
			ans.append(d)
			d -= 1
	z = ans[0]
	p = ans[0]
	for i in range(n):
		z = min(z, ans[i])
		p = max(p, ans[i])
	if z <= 0:
		z = abs(z) + 1
		p = ans[0]
		for i in range(n):
			ans[i] += z
			p = max(p, ans[i])
	print(p)
	for i in range(n):
		print(ans[i], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	seq = [int(x) for x in input()]
	seqID = 0
	result = [0] * n
	(zeroS, oneS) = ([], [])
	for (i, val) in enumerate(seq):
		if val == 0:
			if len(oneS) == 0:
				seqID += 1
				result[i] = seqID
				zeroS.append(seqID)
			else:
				subSeq = oneS.pop()
				result[i] = subSeq
				zeroS.append(subSeq)
		elif len(zeroS) == 0:
			seqID += 1
			result[i] = seqID
			oneS.append(seqID)
		else:
			subSeq = zeroS.pop()
			result[i] = subSeq
			oneS.append(subSeq)
	print(seqID)
	print(*result)


def solve(n, a):
	s = a
	stack = []
	stack2 = []
	ans = [0] * n
	npiles = 0
	index = 0
	for i in range(n):
		if s[i] == '0':
			if len(stack2) == 0:
				npiles += 1
				ans[index] = npiles
				stack.append(npiles)
			else:
				p = stack2.pop(0)
				ans[index] = p
				stack.append(p)
		elif len(stack) == 0:
			npiles += 1
			ans[index] = npiles
			stack2.append(npiles)
		else:
			p = stack.pop(0)
			ans[index] = p
			stack2.append(p)
		index += 1
	print(npiles)
	return ans
t = int(input())
while t:
	n = int(input())
	a = input()
	print(*solve(n, a))
	t -= 1


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	one = deque()
	zero = deque()
	seq = 0
	ans = [-1] * n
	for i in range(n):
		if s[i] == '0':
			if len(zero) != 0:
				one.append(zero.pop())
				ans[i] = one[-1]
			else:
				seq += 1
				one.append(seq)
				ans[i] = seq
		elif len(one) != 0:
			zero.append(one.pop())
			ans[i] = zero[-1]
		else:
			seq += 1
			zero.append(seq)
			ans[i] = seq
	print(max(ans))
	print(*ans)


for tst in range(int(input())):
	n = int(input())
	a = list(input())
	b = [-1] * n
	(q0, q1) = ([], [])
	r = 1
	b[0] = 1
	if a[0] == '0':
		q1.append(1)
	else:
		q0.append(1)
	for i in range(1, n):
		if a[i] == '1':
			if len(q1) > 0:
				v = q1.pop()
				b[i] = v
				q0.append(v)
			else:
				r += 1
				b[i] = r
				q0.append(r)
		elif len(q0) > 0:
			v = q0.pop()
			b[i] = v
			q1.append(v)
		else:
			r += 1
			b[i] = r
			q1.append(r)
	print(r)
	print(' '.join([str(i) for i in b]))


from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = []
	pos1 = deque()
	pos0 = deque()
	for i in range(n):
		new_pos = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(new_pos)
			else:
				new_pos = pos1[-1]
				pos1.pop()
				pos0.append(new_pos)
		elif len(pos0) == 0:
			pos1.append(new_pos)
		else:
			new_pos = pos0[-1]
			pos0.pop()
			pos1.append(new_pos)
		ans.append(new_pos + 1)
	print(len(pos0) + len(pos1))
	print(*ans)


import sys

def solve(S):
	bits = [0 if c == '0' else 1 for c in S]
	DEBUG = False
	if DEBUG:
		print(S)
	n = len(S)
	assigned = [-1] * n
	STACK_Z = []
	STACK_O = []
	first = bits[0]
	cnt = 1
	if first == 0:
		STACK_Z.append(cnt)
	else:
		STACK_O.append(cnt)
	assigned[0] = cnt
	i = 1
	for bit in bits[1:]:
		if bit == 0:
			same = STACK_Z
			other = STACK_O
		else:
			same = STACK_O
			other = STACK_Z
		if len(other) == 0:
			cnt += 1
			same.append(cnt)
			assigned[i] = cnt
		else:
			val = other.pop(-1)
			same.append(val)
			assigned[i] = val
		i += 1
	print(cnt)
	print(' '.join([str(x) for x in assigned]))
	return cnt
IN = [x.strip() for x in sys.stdin.readlines()]
T = int(IN[0])
cur = 1
for ti in range(T):
	S = IN[cur + 1]
	solve(S)
	cur += 2


def solve():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = input()
		zero = []
		one = []
		x = 0
		ans = []
		for i in range(n):
			if s[i] == '0':
				if len(zero) == 0:
					x += 1
					ans.append(x)
					one.append(x)
				else:
					v = zero.pop()
					ans.append(v)
					one.append(v)
			elif len(one) == 0:
				x += 1
				ans.append(x)
				zero.append(x)
			else:
				v = one.pop()
				ans.append(v)
				zero.append(v)
		print(x)
		print(*ans)
solve()


import sys
input = sys.stdin.readline
T = int(input())

class SegmentTree:

	def __init__(self, n, ele):
		self.ide_ele = ele
		self.num = 2 ** (n - 1).bit_length()
		self.seg = [self.ide_ele] * 2 * self.num

	def segfunc(self, x, y):
		return min(x, y)

	def init(self, init_val):
		for i in range(n):
			self.seg[i + self.num - 1] = init_val[i]
		for i in range(self.num - 2, -1, -1):
			self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2])

	def update(self, k, x):
		k += self.num - 1
		self.seg[k] = x
		while k:
			k = (k - 1) // 2
			self.seg[k] = self.segfunc(self.seg[k * 2 + 1], self.seg[k * 2 + 2])

	def query(self, p, q):
		if q <= p:
			return self.ide_ele
		p += self.num - 1
		q += self.num - 2
		res = self.ide_ele
		while q - p > 1:
			if p & 1 == 0:
				res = self.segfunc(res, self.seg[p])
			if q & 1 == 1:
				res = self.segfunc(res, self.seg[q])
				q -= 1
			p = p // 2
			q = (q - 1) // 2
		if p == q:
			res = self.segfunc(res, self.seg[p])
		else:
			res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
		return res
for testcase in range(T):
	n = int(input())
	s = list(input())
	one = SegmentTree(n, 10 ** 10)
	zero = SegmentTree(n, 10 ** 10)
	a = [0] * n
	for i in range(n):
		if s[i] == '0':
			zero.update(i, i)
		else:
			one.update(i, i)
	k = 0
	for i in range(n):
		if a[i] != 0:
			continue
		k += 1
		a[i] = k
		idx = i
		if s[i] == '0':
			flag = True
		else:
			flag = False
		while True:
			if flag:
				p = one.query(idx, n)
				if p == 10 ** 10:
					break
				idx = p
				flag = False
				a[idx] = k
				one.update(idx, 10 ** 10)
			else:
				p = zero.query(idx, n)
				if p == 10 ** 10:
					break
				idx = p
				flag = True
				a[idx] = k
				zero.update(idx, 10 ** 10)
	print(k)
	print(*a)


for _ in range(int(input())):
	n = int(input())
	a = input()
	ans = 0
	l = [0] * n
	code = 1
	zeros = []
	ones = []
	f = 0
	for i in range(n):
		if i == 0:
			l[i] = code
			continue
		if a[i] != a[i - 1]:
			l[i] = code
		elif f == 0:
			code += 1
			l[i] = code
			if a[i] == '0':
				zeros.append(code - 1)
			else:
				ones.append(code - 1)
			f = 1
		elif a[i] == '1' and zeros == []:
			code += 1
			l[i] = code
			ones.append(code - 1)
		elif a[i] == '0' and ones == []:
			code += 1
			l[i] = code
			zeros.append(code - 1)
		elif a[i] == '0':
			l[i] = ones.pop()
			zeros.append(l[i])
		else:
			l[i] = zeros.pop()
			ones.append(l[i])
	print(max(l))
	for x in l:
		print(x, end=' ')
	print('\n')


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

def get_ints_in_variables():
	return map(int, sys.stdin.readline().strip().split())

def get_int():
	return int(sys.stdin.readline())

def get_ints_in_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

def get_string():
	return sys.stdin.readline().strip()

def myceil(x, y):
	return (x + y - 1) // y

def Solution(s, n):
	ans = []
	z = []
	o = []
	for i in range(n):
		newPos = len(z) + len(o) + 1
		if s[i] == '0':
			if len(o) == 0:
				z.append(newPos)
			else:
				z.append(o.pop())
			ans.append(z[-1])
		else:
			if len(z) == 0:
				o.append(newPos)
			else:
				o.append(z.pop())
			ans.append(o[-1])
	print(len(z) + len(o))
	print(*ans)

def main():
	for _ in range(get_int()):
		n = get_int()
		s = get_string()
		Solution(s, n)
main()


import collections

def key_with_max_value(d1):
	return [k for (k, v) in d1.items() if v == max(d1.values())][0]
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	seq = [1] * n
	one_seqs = []
	zero_seqs = []
	if s[0] == '0':
		zero_seqs.append(1)
	else:
		one_seqs.append(1)
	seqs = 1
	for i in range(1, n):
		if s[i] == s[i - 1]:
			if s[i] == '0':
				if one_seqs:
					seq[i] = one_seqs.pop()
					zero_seqs.append(seq[i])
				else:
					seq[i] = seqs + 1
					seqs += 1
					zero_seqs.append(seq[i])
			elif zero_seqs:
				seq[i] = zero_seqs.pop()
				one_seqs.append(seq[i])
			else:
				seq[i] = seqs + 1
				seqs += 1
				one_seqs.append(seq[i])
		else:
			seq[i] = seq[i - 1]
			if s[i] == '0':
				zero_seqs.append(seq[i])
				one_seqs.pop()
			else:
				one_seqs.append(seq[i])
				zero_seqs.pop()
	print(max(seq))
	print(*seq)


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input()))
	if n == 1:
		print(1)
		print(1)
		continue
	z = []
	e = []
	t = s[0] ^ 1
	b = [1]
	c = 1
	if s[0]:
		z += (1,)
	else:
		e += (1,)
	i = 1
	while i < n:
		if s[i] != s[i - 1]:
			if s[i]:
				b += (e[-1],)
				z += (e.pop(),)
				t -= 1
			else:
				b += (z[-1],)
				e += (z.pop(),)
				t += 1
		elif s[i]:
			if t == 0:
				c += 1
				b += (c,)
				z += (c,)
			else:
				b += (e[-1],)
				z += (e.pop(),)
				t -= 1
		elif t == c:
			c += 1
			b += (c,)
			e += (c,)
			t += 1
		else:
			b += (z[-1],)
			e += (z.pop(),)
			t += 1
		i += 1
	print(c)
	print(*b)


import sys
input = sys.stdin.readline
from collections import deque
for _ in range(int(input())):
	n = int(input())
	s = [int(i) for i in input()[:n]]
	ans = []
	c = 0
	d = [[], []]
	for i in s:
		x = 1 - i
		if len(d[x]) > 0:
			peepee = d[x].pop()
			d[i].append(peepee)
		else:
			c += 1
			d[i].append(c)
			peepee = c
		ans.append(peepee)
	print(max(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	ans = [0] * n
	cur = 1
	p1 = []
	p0 = []
	for i in range(len(s)):
		if s[i] == '1':
			if len(p0) > 0:
				x = p0.pop()
				p1.append(x)
				op = x
			else:
				p1.append(cur)
				op = cur
				cur = cur + 1
		if s[i] == '0':
			if len(p1) > 0:
				x = p1.pop()
				p0.append(x)
				op = x
			else:
				p0.append(cur)
				op = cur
				cur = cur + 1
		ans[i] = op
	print(max(ans))
	print(*ans)


from bisect import bisect_left
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	l = int(input())
	s = input().rstrip()
	ans = [0]
	count = 0
	for j in range(1, len(s)):
		if s[j] == '1' and s[j] == s[j - 1]:
			count += 1
		if s[j] == '0' and s[j] == s[j - 1]:
			count -= 1
		ans.append(count)
	mmm = min(ans)
	if mmm < 1:
		for j in range(len(ans)):
			ans[j] += 1 - mmm
	print(max(ans))
	print(*ans)


import sys
fast_reader = sys.stdin.readline
fast_writer = sys.stdout.write

def input():
	return fast_reader().strip()

def print(*argv):
	fast_writer(' '.join((str(i) for i in argv)))
	fast_writer('\n')
for _ in range(int(input())):
	n = int(input())
	s = input()
	l = [int(i) for i in s]
	pp = [[], []]
	ans = [0 for i in range(n)]
	for i in range(n):
		temp = len(pp[0]) + len(pp[1])
		if l[i] == 0:
			if len(pp[1]) == 0:
				pp[0].append(temp)
			else:
				temp = pp[1].pop()
				pp[0].append(temp)
		elif len(pp[0]) == 0:
			pp[1].append(temp)
		else:
			temp = pp[0].pop()
			pp[1].append(temp)
		ans[i] = temp + 1
	print(len(pp[0]) + len(pp[1]))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	s = input()
	(o, z) = ([], [])
	l = []
	c = 0
	for i in range(n):
		if s[i] == '0':
			if len(o) > 0:
				l.append(o.pop())
			else:
				l.append(c + 1)
				c += 1
			z.append(l[-1])
		else:
			if len(z) > 0:
				l.append(z.pop())
			else:
				l.append(c + 1)
				c += 1
			o.append(l[-1])
	print(c)
	print(*l)


rw = int(input())
for qwe in range(rw):
	n = int(input())
	s = input()
	a = []
	tF = []
	tT = []
	tn = 0
	tt = 0
	for i in range(n):
		if s[i] == '0' and tn == tt:
			a.append(tn)
			tn += 1
			tT.append(tn)
			tt += 1
		elif s[i] == '0':
			f = tF[0]
			a.append(f - 1)
			tF.pop(0)
			tT.append(f)
			tt += 1
		elif s[i] == '1' and tt == 0:
			a.append(tn)
			tn += 1
			tF.append(tn)
		elif s[i] == '1':
			f = tT[0]
			a.append(f - 1)
			tT.pop(0)
			tF.append(f)
			tt -= 1
	print(tn)
	for i in a:
		print(i + 1, end=' ')
	print('')


def tc():
	n = int(input())
	s = input()
	k = 0
	zerosi = []
	onesi = []
	ans = []
	for ch in s:
		if ch == '0':
			stack = zerosi
			other = onesi
		else:
			stack = onesi
			other = zerosi
		if stack:
			i = stack.pop()
			ans.append(i)
			other.append(i)
		else:
			k += 1
			ans.append(k)
			other.append(k)
	print(k)
	print(' '.join(map(str, ans)))
T = int(input())
for _ in range(T):
	tc()


from sys import stdin
from sys import stdout
from math import factorial

def solve(run_id):
	n = int(stdin.readline())
	s = stdin.readline()
	(pos0, pos1) = ([], [])
	res = [0] * n
	for i in range(n):
		newpos = len(pos0) + len(pos1)
		if s[i] == '0':
			if len(pos1) == 0:
				pos0.append(newpos)
			else:
				newpos = pos1.pop()
				pos0.append(newpos)
		elif len(pos0) == 0:
			pos1.append(newpos)
		else:
			newpos = pos0.pop()
			pos1.append(newpos)
		res[i] = newpos
	print(len(pos0) + len(pos1))
	for x in res:
		print(x + 1, end=' ')
	print()
for _ in range(int(stdin.readline())):
	solve(_)


t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	l = []
	l1 = []
	l2 = []
	ans = 0
	for j in range(n):
		if s[j] == '0':
			if len(l1):
				a = l1.pop()
				l.append(a)
				l2.append(a)
			else:
				ans += 1
				l2.append(ans)
				l.append(ans)
		elif len(l2):
			a = l2.pop()
			l.append(a)
			l1.append(a)
		else:
			ans += 1
			l1.append(ans)
			l.append(ans)
	print(ans)
	print(*l)


from collections import deque
t = int(input())
while True:
	if t == 0:
		break
	t -= 1
	n = int(input())
	a = [int(i) for i in input()]
	last1Num = 0
	last0Num = 0
	last0sets = deque()
	last1sets = deque()
	if a[0] == 1:
		last1Num = 1
		last1sets.append(1)
	else:
		last0Num = 1
		last0sets.append(1)
	setCount = 1
	vals = [1]
	for i in range(1, n):
		if a[i] == 0:
			if last1Num == 0:
				setCount += 1
				last0sets.append(setCount)
				vals.append(setCount)
				last0Num += 1
			else:
				last1Num -= 1
				vals.append(last1sets[0])
				last1sets.popleft()
				last0sets.append(vals[-1])
				last0Num += 1
		elif last0Num == 0:
			setCount += 1
			last1sets.append(setCount)
			vals.append(setCount)
			last1Num += 1
		else:
			last0Num -= 1
			vals.append(last0sets[0])
			last0sets.popleft()
			last1sets.append(vals[-1])
			last1Num += 1
	print(setCount)
	vals = [str(i) for i in vals]
	print(' '.join(vals))


from collections import deque

def solve():
	N = int(input())
	S = list(map(int, list(input())))
	zero_end = deque([])
	one_end = deque([])
	res = 0
	ans = [0] * N
	for (i, v) in enumerate(S):
		if v == 1:
			if zero_end:
				n = zero_end.popleft()
				ans[i] = n
				one_end.append(n)
			else:
				res += 1
				ans[i] = res
				one_end.appendleft(res)
		elif one_end:
			n = one_end.popleft()
			ans[i] = n
			zero_end.append(n)
		else:
			res += 1
			ans[i] = res
			zero_end.appendleft(res)
	print(res)
	print(*ans)
	return

def main():
	T = int(input())
	for i in range(T):
		solve()
	return
main()


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	s = list(s)
	i = 0
	while i < n:
		s[i] = int(s[i])
		i += 1
	stack0 = []
	stack1 = []
	ans = [0] * n
	ct = 1
	for i in range(0, n):
		if s[i] == 0:
			if len(stack1) == 0:
				stack0.append(ct)
				ans[i] = ct
				ct += 1
			else:
				temp = stack1.pop()
				ans[i] = temp
				stack0.append(temp)
		if s[i] == 1:
			if len(stack0) == 0:
				stack1.append(ct)
				ans[i] = ct
				ct += 1
			else:
				temp = stack0.pop()
				ans[i] = temp
				stack1.append(temp)
	print(ct - 1)
	rel = ''
	for i in ans:
		rel += str(i) + ' '
	print(rel.rstrip())


mod = 1000000007
t = int(input())
while t:
	t -= 1
	n = int(input())
	s = input()
	cnt = 1
	sz = []
	so = []
	arr = [0] * n
	for i in range(n):
		if s[i] == '0':
			if not so:
				arr[i] = cnt
				sz.append(cnt)
				cnt += 1
			else:
				dd = so.pop()
				sz.append(dd)
				arr[i] = dd
		elif not sz:
			arr[i] = cnt
			so.append(cnt)
			cnt += 1
		else:
			dd = sz.pop()
			so.append(dd)
			arr[i] = dd
	print(cnt - 1)
	print(*arr)


a = input()
for x in range(int(a)):
	c = input()
	b = input()
	list1 = []
	list2 = []
	now = 0
	tag1 = ''
	ans = [0] * int(c)
	for i in range(len(b)):
		if b[i] == '0':
			if len(list1) == 0:
				now += 1
				ans[i] = now
			else:
				ans[i] = ans[list1.pop()]
			list2.append(i)
		else:
			if len(list2) == 0:
				now += 1
				ans[i] = now
			else:
				ans[i] = ans[list2.pop()]
			list1.append(i)
	tag = len(set(ans))
	print(tag)
	for i in range(len(ans)):
		if i != len(ans) - 1:
			print(ans[i], end=' ')
		else:
			print(ans[i])


from typing import List, Mapping, Set, Tuple

def solve(bits: str) -> Tuple[int, List[int]]:
	subsequences: int = 0
	inv: Mapping[str, str] = {'0': '1', '1': '0'}
	sequences_that_end_in: Mapping[str, Set[int]] = {'0': set(), '1': set()}
	assignments: List[int] = []
	for bit in bits:
		if not sequences_that_end_in[inv[bit]]:
			subsequences += 1
			assignments.append(subsequences)
			sequences_that_end_in[bit].add(subsequences)
		else:
			seq_id = sequences_that_end_in[inv[bit]].pop()
			assignments.append(seq_id)
			sequences_that_end_in[bit].add(seq_id)
	return (subsequences, assignments)
for _ in range(int(input())):
	__ = input()
	(n, assignments) = solve(str(input()))
	print(n)
	print(' '.join(map(str, assignments)))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	s = input()
	b = [[] for __ in range(2)]
	val = 0
	ans = []
	for each in s:
		if len(b[int(each)]):
			b[1 - int(each)] += [b[int(each)].pop()]
			ans += [b[1 - int(each)][-1]]
		else:
			val += 1
			b[1 - int(each)] += [val]
			ans += [val]
	print(val)
	print(*ans)


for s in [*open(0)][2::2]:
	(a, k, r) = ([[], []], 0, [])
	for v in map(int, s[:-1]):
		if not a[v]:
			k += 1
			a[v] += [k]
		r += [a[v][-1]]
		a[1 - v] += [a[v].pop()]
	print(k, *r)


t = int(input())
for t_c in range(t):
	n = int(input())
	s = input()
	s = [int(i) for i in s]
	ones = []
	seqs = [[], []]
	total = 0
	pr = []
	for c in s:
		if len(seqs[c]) > 0:
			r = seqs[c].pop()
			seqs[not c].append(r)
			pr.append(r)
		else:
			total += 1
			seqs[not c].append(total)
			pr.append(total)
	print(total)
	for p in pr:
		print(p, end=' ')
	print()


def fun(s):
	count_0 = []
	count_1 = []
	ans = [None for i in range(len(s))]
	for i in range(len(s)):
		curr = s[i]
		if curr == '1':
			if count_0:
				ans[i] = str(count_0.pop(-1))
				count_1.append(int(ans[i]))
			else:
				ans[i] = str(len(count_0) + len(count_1) + 1)
				count_1.append(int(ans[i]))
		elif count_1:
			ans[i] = str(count_1.pop(-1))
			count_0.append(int(ans[i]))
		else:
			ans[i] = str(len(count_0) + len(count_1) + 1)
			count_0.append(int(ans[i]))
	return (len(count_0) + len(count_1), ans)
for _ in range(int(input())):
	n = input()
	s = input()
	(a, b) = fun(s)
	print(a)
	print(' '.join(b))


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		n = iin()
		s = sin()
		d = deque([])
		nz = set()
		no = set()
		count = 1
		for i in range(n):
			if len(nz) == 0 and len(no) == 0:
				if s[i] == '1':
					nz.add(1)
				else:
					no.add(1)
				d.append(1)
				count += 1
			elif s[i] == '1':
				if len(no) == 0:
					d.append(count)
					nz.add(count)
					count += 1
				else:
					x = no.pop()
					nz.add(x)
					d.append(x)
			elif len(nz) == 0:
				d.append(count)
				no.add(count)
				count += 1
			else:
				x = nz.pop()
				no.add(x)
				d.append(x)
		print(count - 1)
		print(*d)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def solve(s, n):
	(one, zero) = ([], [])
	if s[0] == '1':
		one.append(1)
	else:
		zero.append(1)
	counter = 1
	ind = 1
	ans = [0] * n
	ans[0] = 1
	while ind < n:
		if s[ind] == '0':
			if len(one):
				ans[ind] = one.pop()
				zero.append(ans[ind])
			else:
				counter += 1
				zero.append(counter)
				ans[ind] = counter
		elif len(zero):
			ans[ind] = zero.pop()
			one.append(ans[ind])
		else:
			counter += 1
			ans[ind] = counter
			one.append(counter)
		ind += 1
	print(counter)
	for val in ans:
		print(val, end=' ')
	print('\n', end='')
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	solve(s, len(s))


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input()]
	st = [[], []]
	ans = []
	cur = 0
	for i in a:
		if i == 1:
			if not st[0]:
				st[i].append(cur + 1)
			else:
				st[i].append(st[0].pop())
			cur = max(cur, st[i][-1])
		else:
			if not st[1]:
				st[i].append(cur + 1)
			else:
				st[i].append(st[1].pop())
			cur = max(cur, st[i][-1])
		ans.append(st[i][-1])
	print(max(ans))
	print(*ans)


import collections
for _ in range(int(input())):
	n = int(input())
	s = str(input())
	d = collections.defaultdict(list)
	(v, l) = ([], [])
	for i in range(n):
		if i == 0:
			v.append(1)
			d[1 - int(s[i])].append(1)
			grp = 1
		elif d[int(s[i])]:
			k = d[int(s[i])].pop()
			v.append(k)
			d[1 - int(s[i])].append(k)
		else:
			v.append(grp + 1)
			d[1 - int(s[i])].append(grp + 1)
			grp += 1
	print(grp)
	print(*v)


from math import *
sInt = lambda : int(input())
mInt = lambda : map(int, input().split())
lInt = lambda : list(map(int, input().split()))
t = sInt()
for _ in range(t):
	n = sInt()
	a = input()
	a = list(a)
	(o, z) = ([], [])
	cnt = 0
	ans = []
	for i in a:
		if i == '0':
			if len(o) == 0:
				cnt += 1
				ans.append(cnt)
				z.append(cnt)
			else:
				p = o.pop()
				ans.append(p)
				z.append(p)
		elif len(z) == 0:
			cnt += 1
			ans.append(cnt)
			o.append(cnt)
		else:
			p = z.pop()
			ans.append(p)
			o.append(p)
	print(max(ans))
	print(*ans, sep=' ')


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
for _ in range(int(input())):
	n = int(input())
	a = []
	b = []
	x = 1
	z = [0 for i in range(n)]
	s = input()
	for i in range(n):
		if s[i] == '0':
			if len(a) > 0:
				t = a.pop()
				z[i] = t
				b.append(t)
			else:
				b.append(x)
				z[i] = x
				x += 1
		elif len(b) > 0:
			t = b.pop()
			z[i] = t
			a.append(t)
		else:
			a.append(x)
			z[i] = x
			x += 1
	print(max(z))
	print(*z)


t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	arr = []
	for ch in s:
		arr.append(int(ch))
	(ans, temp, exp) = ([], [[], []], 0)
	for num in arr:
		other = 1 - num
		if len(temp[other]) != 0:
			p = temp[other].pop()
			temp[num].append(p)
		else:
			exp += 1
			temp[num].append(exp)
			p = exp
		ans.append(p)
	print(max(ans))
	print(*ans)


from sys import stdin, stdout
from collections import defaultdict
input = lambda : stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	s = input()
	lst = [1]
	lst0 = []
	lst1 = []
	if s[0] == '0':
		lst0.append(1)
	else:
		lst1.append(1)
	nd = 1
	for i in range(1, n):
		if s[i] == '0':
			try:
				a = lst1.pop()
				lst0.append(a)
				lst.append(a)
			except:
				nd += 1
				lst0.append(nd)
				lst.append(nd)
		else:
			try:
				a = lst0.pop()
				lst1.append(a)
				lst.append(a)
			except:
				nd += 1
				lst1.append(nd)
				lst.append(nd)
	print(nd)
	print(*lst)


t = int(input())
from collections import deque
for _ in range(t):
	n = int(input())
	one = deque()
	zero = deque()
	ans = 0
	z = 0
	s = input()
	this = []
	for i in range(len(s)):
		if s[i] == '0':
			if not one:
				z += 1
				ans += 1
				this.append(z)
				zero.append(z)
				continue
			else:
				k = one.popleft()
				this.append(k)
				zero.append(k)
				continue
		elif s[i] == '1':
			if not zero:
				z += 1
				ans += 1
				this.append(z)
				one.append(z)
				continue
			else:
				k = zero.popleft()
				this.append(k)
				one.append(k)
	print(ans)
	for item in this:
		print(item, end=' ')
	print(' ')


from sys import stdin, stdout

def ufind(u_a, i):
	if i == u_a[i]:
		return i
	u_a[i] = ufind(u_a, u_a[i])
	return u_a[i]

def union(u_a, i, j):
	ri = ufind(u_a, i)
	rj = ufind(u_a, j)
	u_a[ri] = u_a[rj]

def binary_string_to_subsequences2(n, s):
	u_a = [i for i in range(n)]
	q_a = [[] for _ in range(2)]
	q_a[ord(s[0]) - ord('0')].append(0)
	for i in range(1, n):
		v = ord(s[i]) - ord('0')
		if q_a[v ^ 1]:
			union(u_a, i, q_a[v ^ 1].pop())
		q_a[v].append(i)
	ans1 = len(q_a[0]) + len(q_a[1])
	ans2 = []
	for i in range(n):
		ans2.append(ufind(u_a, i) + 1)
	return [ans1, ans2]

def binary_string_to_subsequences(n, s):
	g = 1
	q_a = [[] for _ in range(2)]
	q_a[ord(s[0]) - ord('0')].append(g)
	ans2 = [g]
	for i in range(1, n):
		v = ord(s[i]) - ord('0')
		if q_a[v ^ 1]:
			q_a[v].append(q_a[v ^ 1].pop())
		else:
			g += 1
			q_a[v].append(g)
		ans2.append(q_a[v][-1])
	ans1 = len(q_a[0]) + len(q_a[1])
	return [ans1, ans2]
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	s = stdin.readline().strip()
	ans = binary_string_to_subsequences(n, s)
	stdout.write(str(ans[0]) + '\n')
	stdout.write(' '.join(map(str, ans[1])) + '\n')


from sys import stdin, stdout
import math
input = stdin.readline

def print(*args, end='\n'):
	s = []
	for i in args:
		s.append(str(i) + ' ')
	s = ''.join(s)
	stdout.write(s + end)

def solve():
	n = int(input())
	s = input()
	ans = []
	(l0, l1) = ([], [])
	maxx = 0
	for i in range(n):
		cur = len(l1) + len(l0)
		if s[i] == '0':
			if not l1:
				cur += 1
				ans.append(cur)
				l0.append(i)
			else:
				l0.append(l1.pop())
				ans.append(ans[l0[-1]])
		elif not l0:
			cur += 1
			ans.append(cur)
			l1.append(i)
		else:
			l1.append(l0.pop())
			ans.append(ans[l1[-1]])
		if cur > maxx:
			maxx = cur
	print(maxx)
	for i in ans:
		print(i, end=' ')
	print()
tt = 1
tt = int(input())
for __ in range(tt):
	solve()


for nt in range(int(input())):
	n = int(input())
	s = input()
	ans = []
	(o, z) = (0, 0)
	d = {}
	l = {0: {}, 1: {}}
	for i in range(n):
		if s[i] == '0':
			d[i] = o + 1
			if o == len(ans):
				ans.append(['0'])
				l[0][o] = 1
				o += 1
			else:
				ans[o].append('0')
				z = o
				l[0][o] = 1
				if o in l[1]:
					del l[1][o]
				o = len(ans)
				for k in l[1]:
					o = k
					break
		else:
			d[i] = z + 1
			if z == len(ans):
				ans.append(['1'])
				l[1][z] = 1
				z += 1
			else:
				ans[z].append('1')
				o = z
				l[1][z] = 1
				if z in l[0]:
					del l[0][z]
				z = len(ans)
				for k in l[0]:
					z = k
					break
	print(len(ans))
	for i in range(n):
		print(d[i], end=' ')
	print()


def Func(a):
	zeros = []
	ones = []
	nums = []
	next_num = 1
	for elem in a:
		if elem == '0':
			if not ones:
				nums.append(next_num)
				zeros.append(next_num)
				next_num += 1
			else:
				current_num = ones.pop()
				zeros.append(current_num)
				nums.append(current_num)
		elif not zeros:
			nums.append(next_num)
			ones.append(next_num)
			next_num += 1
		else:
			current_num = zeros.pop()
			ones.append(current_num)
			nums.append(current_num)
	print(next_num - 1)
	print(' '.join(map(str, nums)))
t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	Func(a)