This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.

You are given a string $s$ consisting of $n$ lowercase Latin letters.

You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$).

After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.

The goal is to make the string sorted, i.e. all characters should be in alphabetical order.

Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.


-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$.

The second line of the input contains the string $s$ consisting of exactly $n$ lowercase Latin letters.


-----Output-----

In the first line print one integer $res$ ($1 \le res \le n$) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.

In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array $c$ of length $n$, where $1 \le c_i \le res$ and $c_i$ means the color of the $i$-th character.


-----Examples-----
Input
9
abacbecfd

Output
2
1 1 2 1 2 1 2 1 2 

Input
8
aaabbcbb

Output
2
1 2 1 2 1 2 1 1

Input
7
abcdedc

Output
3
1 1 1 1 1 2 3 

Input
5
abcde

Output
1
1 1 1 1 1

Difficulty: HARD
Tags: Dynamic programming

Data structures
Skill types: Dynamic programming

Data structures

Starter code:

Solutions:
n = int(input())
s = input()
c = 1
k = [0 for i in range(26)]
code = ord('a')
k[0] = 1
ans = []
for i in range(n):
	letter = ord(s[i]) - code
	if k[letter] != 0:
		ans.append(k[letter])
	else:
		for j in range(letter, -1, -1):
			if k[j] != 0:
				ans.append(k[j])
				k[letter] = k[j]
				k[j] = 0
				break
			if j == 0:
				c += 1
				k[letter] = c
				ans.append(c)
print(c)
print(*ans)


n = int(input())
s = input()
arr = [0 for i in range(n)]
grps = []
col = 0
for i in range(len(s)):
	if grps == []:
		grps.append(s[i])
		arr[i] = 1
		col += 1
	else:
		found = 0
		for j in range(len(grps)):
			if ord(s[i]) >= ord(grps[j]):
				found = 1
				grps[j] = s[i]
				arr[i] = j + 1
				break
		if found == 0:
			grps.append(s[i])
			col += 1
			arr[i] = col
print(col)
for i in range(n):
	print(arr[i], end=' ')
print()


input()
s = input()
a = []
ans = [0] * len(s)
for (i, c) in enumerate(s):
	if not a or c < a[-1]:
		a.append(c)
		ans[i] = len(a)
	else:
		l = 0
		r = len(a) - 1
		while l < r:
			mid = l + r >> 1
			if a[mid] > c:
				l = mid + 1
			else:
				r = mid
		a[l] = c
		ans[i] = l + 1
print(len(a))
print(*ans)


input()
arr = input().strip()
ans = []
color = 0
mx = [0 for i in range(26)]
for i in arr:
	c = ord(i) - 97
	_max = 0
	for j in range(c + 1, 26):
		_max = max(_max, mx[j])
	ans.append(_max + 1)
	color = max(color, ans[-1])
	mx[c] = max(mx[c], _max + 1)
print(color)
for i in ans:
	print(i, end=' ')


n = int(input())
s = list(input())
dg = 10 ** 6
for i in range(n):
	s[i] = ord(s[i]) * dg + i
s.sort()

def init_max(init_max_val):
	for i in range(n):
		seg_max[i + num_max - 1] = init_max_val[i]
	for i in range(num_max - 2, -1, -1):
		seg_max[i] = max(seg_max[2 * i + 1], seg_max[2 * i + 2])

def update_max(k, x):
	k += num_max - 1
	seg_max[k] = x
	while k:
		k = (k - 1) // 2
		seg_max[k] = max(seg_max[k * 2 + 1], seg_max[k * 2 + 2])

def query_max(p, q):
	if q <= p:
		return ide_ele_max
	p += num_max - 1
	q += num_max - 2
	res = ide_ele_max
	while q - p > 1:
		if p & 1 == 0:
			res = max(res, seg_max[p])
		if q & 1 == 1:
			res = max(res, seg_max[q])
			q -= 1
		p = p // 2
		q = (q - 1) // 2
	if p == q:
		res = max(res, seg_max[p])
	else:
		res = max(max(res, seg_max[p]), seg_max[q])
	return res
ide_ele_max = 0
num_max = 2 ** (n - 1).bit_length()
seg_max = [ide_ele_max] * 2 * num_max
res = [0] * n
for e in s:
	ind = e % dg
	ad = query_max(ind, n)
	res[ind] = ad + 1
	update_max(ind, ad + 1)
print(max(res))
print(*res)


n = int(input())
s = input()
ans = [1]
cc = 0
color = ['z'] * 26
color[0] = s[0]
for i in range(1, n):
	flag = False
	for j in range(cc + 1):
		if color[j] <= s[i]:
			ans.append(j + 1)
			flag = True
			color[j] = s[i]
			break
	if not flag:
		cc += 1
		color[cc] = s[i]
		ans.append(cc + 1)
print(cc + 1)
for i in range(n):
	print(ans[i], end=' ')


def hello_nigga():
	n = int(input())
	s = input()
	LAST = {1: 'a'}
	COLORS = {1: []}
	cnum = 1
	for i in range(n):
		nice = 0
		for j in range(1, cnum + 1):
			if s[i] >= LAST[j]:
				LAST[j] = s[i]
				COLORS[j].append(i)
				nice = 1
				break
		if not nice:
			cnum += 1
			LAST[cnum] = s[i]
			COLORS[cnum] = [i]
	ans = [0] * n
	for i in range(1, cnum + 1):
		for j in range(len(COLORS[i])):
			ans[COLORS[i][j]] = i
	print(cnum)
	print(*ans)
if 'compiler is alive':
	if 'it has sence' and 'the wether is nice':
		hello_nigga()


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 factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

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)
mod = 998244353
INF = float('inf')
from bisect import bisect_left, insort

def main():
	n = N()
	s = input()
	s = [-ord(i) for i in s]
	rec = [INF] * n
	res = []
	ma = 1
	for i in s:
		p = bisect_left(rec, i)
		res.append(p + 1)
		rec[p] = i
		ma = max(ma, p + 1)
	print(ma)
	print(*res)
main()


import sys
import math
from collections import defaultdict, Counter, deque
n = int(input())
s = list(input())
colour = [1] * n
dp = [0] * 26
for i in range(n):
	for j in range(25, ord(s[i]) - 97, -1):
		colour[i] = max(colour[i], dp[j] + 1)
	dp[ord(s[i]) - 97] = max(dp[ord(s[i]) - 97], colour[i])
print(max(colour))
print(*colour)


import os
import sys
from atexit import register
from io import StringIO
sys.stdout = StringIO()
register(lambda : os.write(1, sys.stdout.getvalue().encode()))
import math
n = int(input())
s = input()
x = [ord(c) - 97 for c in s]
c = [1]
res = 1
r = [x[0]]
for k in x[1:]:
	appended = False
	for cl in range(res):
		if k >= r[cl]:
			c.append(cl + 1)
			r[cl] = k
			appended = True
			break
	if not appended:
		res += 1
		r.append(k)
		c.append(res)
print(res)
print(' '.join([str(k) for k in c]))


from sys import stdin, stdout
input = stdin.readline

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

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

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

def ins():
	return input()[:-1]
n = ii()
st = ins()
lis = [0] * (n + 1)
lis[1] = st[0]
r = 1
ans = [1]
for i in st[1:]:
	if i >= lis[1]:
		lis[1] = i
		ans.append(1)
	elif i < lis[r]:
		r += 1
		lis[r] = i
		ans.append(r)
	else:
		left = 1
		right = r
		while left < right:
			mid = (left + right) // 2
			if i < lis[mid]:
				left = mid + 1
			else:
				right = mid
		ans.append(left)
		lis[left] = i
print(r)
print(*ans)


import sys
input = sys.stdin.readline
from collections import *
n = int(input())
s = input()[:-1]
acc = [[0] * (n + 1) for _ in range(26)]
for i in range(n):
	for j in range(26):
		acc[j][i + 1] = acc[j][i] + (1 if ord(s[i]) - ord('a') == j else 0)
dp = [1] * n
M = [0] * 26
M[0] = 1
for i in range(n - 1, -1, -1):
	for j in range(ord(s[i]) - ord('a')):
		if acc[j][n] - acc[j][i + 1] > 0:
			dp[i] = max(dp[i], M[j] + 1)
	M[ord(s[i]) - ord('a')] = max(M[ord(s[i]) - ord('a')], dp[i])
print(max(dp))
print(*dp)


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial, gcd
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
import sys, io, os
input = sys.stdin.readline
inf = float('inf')
mod = 10 ** 9 + 7

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

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b

def lis_length(nums, cmp=lambda x, y: x < y):
	P = [0] * len(nums)
	M = [0] * (len(nums) + 1)
	L = 0
	for i in range(len(nums)):
		(lo, hi) = (1, L)
		while lo <= hi:
			mid = (lo + hi) // 2
			if cmp(nums[M[mid]], nums[i]):
				lo = mid + 1
			else:
				hi = mid - 1
		newL = lo
		P[i] = M[newL - 1]
		M[newL] = i
		L = max(L, newL)
	lislen = [1 for i in P]
	for i in range(1, len(nums)):
		if P[i] == 0:
			if cmp(nums[P[i]], nums[i]):
				lislen[i] = lislen[P[i]] + 1
			else:
				lislen[i] = lislen[P[i]]
		else:
			lislen[i] = lislen[P[i]] + 1
	return lislen
t = 1
for i in range(t):
	n = int(input())
	s = input().strip()
	lislen = lis_length(s[::-1])[::-1]
	print(max(lislen))
	print(*lislen)


alp = 'abcdefghijklmnopqrstuvwxyz'
dic = {}
for (i, s) in enumerate(alp):
	dic[s] = i
lis = [0] * 27
n = int(input())
S = input()
ans = []
for (i, s) in enumerate(S):
	ind = dic[s]
	ans.append(max(lis[ind + 1:]) + 1)
	lis[ind] = ans[-1]
print(max(ans))
print(' '.join(map(str, ans)))


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 ** 18
MOD = 10 ** 9 + 7

def bisearch_min(mn, mx, func):
	ok = mx
	ng = mn
	while ng + 1 < ok:
		mid = (ok + ng) // 2
		if func(mid):
			ok = mid
		else:
			ng = mid
	return ok

def check(m):
	if m == len(B):
		return True
	if B[m][-1][0] <= a:
		return True
	else:
		return False
N = INT()
A = [ord(c) - 97 for c in input()]
B = [[] for i in range(1)]
B[0].append((A[0], 0))
for (i, a) in enumerate(A[1:], 1):
	idx = bisearch_min(-1, len(B), check)
	if idx == len(B):
		B.append([(a, i)])
	else:
		B[idx].append((a, i))
ans = [0] * N
for (a, li) in enumerate(B):
	for (_, idx) in li:
		ans[idx] = a + 1
print(len(B))
print(*ans)


(n, s) = (int(input()), input())
k = ['a']
ans = ''
maxColor = 1
for symb in s:
	k.append('a')
	for i in range(len(k)):
		if symb >= k[i]:
			ans += str(i + 1) + ' '
			if i + 1 > maxColor:
				maxColor = i + 1
			k[i] = symb
			break
print(maxColor)
print(ans)


from sys import stdin, stdout
t = 1
for _ in range(t):
	n = int(input())
	s = input()
	ans = []
	dict = {}
	count = 0
	for i in s:
		count += 1
		maxi = -1
		taken = set()
		for j in range(97 + 25, 96, -1):
			if chr(j) in dict and chr(j) > i:
				taken.add(dict[chr(j)][1])
		j = 0
		while 1:
			j += 1
			if j not in taken:
				ans.append(j)
				dict[i] = (count, j)
				break
	print(len(set(ans)))
	print(*ans)


class RangeMinimumQuery:

	def __init__(self, n, func=min, inf=float('inf')):
		self.n0 = 2 ** (n - 1).bit_length()
		self.op = func
		self.inf = inf
		self.data = [self.inf] * (2 * self.n0)

	def query(self, l, r):
		l += self.n0
		r += self.n0
		res = self.inf
		while l < r:
			if r & 1:
				r -= 1
				res = self.op(res, self.data[r - 1])
			if l & 1:
				res = self.op(res, self.data[l - 1])
				l += 1
			l >>= 1
			r >>= 1
		return res

	def update(self, i, x):
		i += self.n0 - 1
		self.data[i] = x
		while i:
			i = ~-i // 2
			self.data[i] = self.op(self.data[2 * i + 1], self.data[2 * i + 2])
n = int(input())
s = input()
a = [(c, i) for (i, c) in enumerate(s)]
a.sort()
RMQ = RangeMinimumQuery(n, max, 0)
col = [0] * n
for (_, i) in a:
	c = RMQ.query(i, n) + 1
	col[i] = c
	RMQ.update(i, c)
max_col = RMQ.query(0, n)
print(max_col)
print(*col)


n = int(input())
s = [ord(i) - ord('a') + 1 for i in input()]
clr = ['1'] * n
current = 1
x = s[0]
last = [27, 1]
for i in range(n):
	if s[i] >= x:
		x = s[i]
		last[1] = s[i]
	else:
		check = [s[i] < j for j in last]
		if False in check:
			c = check.index(False)
			last[c] = s[i]
		else:
			current += 1
			c = current
			last.append(s[i])
		clr[i] = str(c)
print(len(set(clr)))
print(' '.join(clr))


import sys
input = sys.stdin.readline
n = int(input())
S = input().strip()
A = [97 - (ord(s) - 96) for s in S]
DP = [float('inf')] * n
ANS = []
import bisect
for a in A:
	pos = bisect.bisect_left(DP, a)
	ANS.append(pos + 1)
	DP[pos] = a
print(max(ANS))
print(*ANS)


import sys
input = sys.stdin.readline

def main():
	N = int(input())
	S = input().strip()
	color = []
	ans = []
	for (i, s) in enumerate(S):
		if i == 0:
			color.append(ord(s) - ord('a'))
			ans.append(1)
		else:
			for j in range(len(color)):
				if ord(s) - ord('a') >= color[j]:
					color[j] = ord(s) - ord('a')
					ans.append(j + 1)
					break
			else:
				ans.append(len(color) + 1)
				color.append(ord(s) - ord('a'))
	else:
		print(len(color))
		print(*ans)
main()


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
from queue import PriorityQueue
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
n = int(input())
s = input().strip()
l = [97 - (ord(i) - 96) for i in s]
dp = [float('inf')] * n
ans = []
for i in l:
	posn = bisect_left(dp, i)
	ans.append(posn + 1)
	dp[posn] = i
print(max(ans))
print(*ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
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=2 ** 30, func=lambda a, b: min(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

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
n = int(input())
d = dict()
for i in range(97, 124):
	d[chr(i)] = 0
l = input()
d[l[0]] += 1
ans = [0] * n
ans[0] = d[l[0]]
for i in range(1, n):
	for j in sorted(d.keys(), reverse=True):
		if j > l[i]:
			ans[i] = max(ans[i], d[j] + 1)
		else:
			break
	d[l[i]] = ans[i]
print(max(ans))
print(*ans, sep=' ')


def solve():
	n = int(input())
	s = input()
	color = []
	for i in range(n):
		color.append(1)
	prevMaxColor = []
	for i in range(30):
		prevMaxColor.append(0)
	for i in reversed(range(n)):
		c = ord(s[i]) - ord('a')
		for j in range(0, c):
			color[i] = max(color[i], prevMaxColor[j] + 1)
		prevMaxColor[c] = max(color[i], prevMaxColor[c])
	print(max(color))
	for c in color:
		print(c, end=' ')
solve()


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

def num():
	return int(input())
from itertools import tee

def pairwise(it):
	(a, b) = tee(it)
	next(b, None)
	return zip(a, b)
n = num()
s = input()
qq = []
ans = []
for c in s:
	for (j, q) in enumerate(qq):
		if c >= q:
			qq[j] = c
			ans.append(j + 1)
			break
	else:
		qq.append(c)
		ans.append(len(qq))
print(len(qq))
print(' '.join(map(str, ans)))


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial, gcd
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
from heapq import heapify, heappop, heappush
import sys, io, os
input = sys.stdin.readline
inf = float('inf')
mod = 10 ** 9 + 7

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

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
import string
abcd = string.ascii_lowercase
t = 1
for i in range(t):
	n = int(input())
	s = input().strip()
	dicta = defaultdict(int)
	ans = [1 for i in s]
	for (indexa, i) in enumerate(reversed(s)):
		for j in abcd:
			if j < i:
				ans[n - indexa - 1] = max(ans[n - indexa - 1], dicta[j] + 1)
		dicta[i] = ans[n - indexa - 1]
	print(max(ans))
	print(*ans)


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify
mod = 10 ** 9 + 7
INF = float('inf')

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

def inpl():
	return list(map(int, sys.stdin.readline().split()))
n = inp()
s = list(input())
for (i, x) in enumerate(s):
	s[i] = ord(x) - 97
s = s[::-1]
lis = [INF] * 30
color = [-1] * n
for (i, x) in enumerate(s):
	ind = bisect_left(lis, x)
	color[i] = ind + 1
	lis[ind] = x
print(max(color))
print(*color[::-1])


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 prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	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 not True else 1):
	n = int(input())
	s = input()
	ans = [0] * n
	colors = ['a'] * 50
	for i in range(n):
		for j in range(50):
			if ord(s[i]) >= ord(colors[j]):
				colors[j] = s[i]
				ans[i] = j + 1
				break
	print(max(ans))
	print(*ans)


n = int(input())
s = input()
col = [1] * n
prev = [0] * 26
for i in range(n):
	code = ord(s[i]) - ord('a')
	if code != 25:
		col[i] = max(prev[code + 1:]) + 1
	prev[code] = col[i]
print(max(col))
print(*col)


def binSearch(a, n):
	n = ord(n)
	(i, j) = (0, len(a) - 1)
	while i != j:
		if (j - i) % 2 == 1:
			if ord(a[i + (j - i) // 2]) > n:
				i = i + (j - i) // 2 + 1
			else:
				j = i + (j - i) // 2
		elif ord(a[i + (j - i) // 2]) > n:
			i = i + (j - i) // 2
		else:
			j = i + (j - i) // 2
	return i
(n, s) = (int(input()), input())
k = ['a', 'a']
ans = ''
maxColor = 1
for symb in s:
	i = binSearch(k, symb)
	ans += str(i + 1) + ' '
	if i + 1 > maxColor:
		maxColor = i + 1
		k.append('a')
	k[i] = symb
print(maxColor)
print(ans)


n = int(input())
a = list(map(lambda c: ord(c) - 97, input()))
color = [0] * 26
ans = [0] * n
last = -1
for (i, c) in enumerate(a):
	col = 0
	if last <= c:
		last = c
		if color[c] == 0:
			col = 1
		else:
			col = color[c] & -color[c]
	else:
		col = 1
		for j in range(last, c, -1):
			while col & color[j]:
				col <<= 1
	color[c] |= col
	ans[i] = len(bin(col)) - 2
print(max(ans))
print(*ans)


from sys import stdin
input = stdin.readline
n = int(input())
s = input().strip()
tmp = [s[0]] + ['' for i in range(25)]
ans = [1]
for i in range(1, len(s)):
	for j in range(26):
		if tmp[j] <= s[i]:
			ans.append(j + 1)
			tmp[j] = s[i]
			break
print(max(ans))
print(*ans)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
a = input()
ck = []
ans = [0] * n
for (i, v) in enumerate(a):
	for j in range(len(ck)):
		if ck[j][-1] <= v:
			ck[j].append(v)
			ans[i] = j + 1
			break
	if not ans[i]:
		ck.append([v])
		ans[i] = len(ck)
print(len(ck))
print(*ans)


import math
import sys
from collections import defaultdict

def stdinWrapper():
	data = '200\nraaaaabbbccccccccccdddddeeeeeeeeeeeeeeffffffffffggggggggghhhhhiiiiiiiiijjjjkkkkkkkkkkllllllllmmmmmmmmnnnnnnnooooooooppppppqqqqqqqqqqrrrrrrrrssssttttttttttuuuuuuuuvvvvvvwwwwwwxxxxxxxyyyyyyyzzzzzzzzzzzz\n'
	for line in data.split('\n'):
		yield line
if '--debug' not in sys.argv:

	def stdinWrapper():
		while True:
			yield input()
inputs = stdinWrapper()

def inputWrapper():
	return next(inputs)

def getType(_type):
	return _type(inputWrapper())

def getArray(_type):
	return [_type(x) for x in inputWrapper().split()]
l = getType(int)
_str = getType(str)
dp = [1] * l
maxdp = [0] * 26
dp = [1] * len(_str)
p = [-1] * len(_str)
for i in range(len(_str)):
	for c in range(ord(_str[i]) - ord('a') + 1, 26):
		dp[i] = max(dp[i], maxdp[c] + 1)
	maxdp[ord(_str[i]) - ord('a')] = max(dp[i], maxdp[ord(_str[i]) - ord('a')])
print(max(dp))
print(' '.join([str(x) for x in dp]))


import sys
sys.setrecursionlimit(10 ** 6)
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]

def main():
	n = II()
	s = SI()
	col = [0] * 27
	ans = [0] * n
	a = ord('a')
	for (i, c) in enumerate(s):
		code = ord(c) - a
		cur = max(col[code + 1:]) + 1
		ans[i] = cur
		col[code] = cur
	print(max(col))
	print(*ans)
main()


n = int(input())
s = input()
tmp = [s[0]] + ['' for i in range(25)]
ans = [1]
for i in range(1, len(s)):
	for j in range(26):
		if tmp[j] <= s[i]:
			ans.append(j + 1)
			tmp[j] = s[i]
			break
print(max(ans))
print(*ans)


n = int(input())
s = input()
f = [0 for _ in range(26)]
res = [1 for _ in range(n)]
for i in range(n):
	c = ord(s[i]) - ord('a')
	for j in range(c + 1, 26):
		res[i] = max(res[i], f[j] + 1)
	f[c] = max(f[c], res[i])
maxres = max(res)
print(maxres)
for i in res:
	print(i, end=' ')


input()
string = input()
colors = [0] * 26
res = []
visited = set()
for char in string:
	i1 = ord(char) - ord('a')
	color = 0
	for v in visited:
		i2 = ord(v) - ord('a')
		if char < v:
			color = max(color, colors[i2])
	color += 1
	colors[i1] = color
	res.append(color)
	visited.add(char)
print(max(colors))
print(' '.join((str(i) for i in res)))


def main():
	n = int(input())
	ss = list(zip(input(), range(0, n)))
	res = [1] * n
	max_colour = 1
	nextx = [0] * 26
	colours_after = [[True] + [False] * 26 for _ in range(26)]
	for i in range(n):
		ch = ord(ss[i][0]) - ord('a')
		opos = ss[i][1]
		nx = nextx[ch]
		col = colours_after[ch].index(False)
		if col > max_colour:
			max_colour = col
		res[opos] = col
		for c in range(ch):
			colours_after[c][col] = True
		for c in range(ch, 26):
			nextx[c] = min(nextx[c], nx + 1)
	print(max_colour)
	print(' '.join(map(str, res)))
main()


from bisect import *
input()
(l, *a) = ([],)
for c in [-ord(i) for i in input()]:
	i = bisect_left(l, c)
	a += (i + 1,)
	if i < len(l):
		l[i] = c
	else:
		l += (c,)
print(len(l))
print(*a)


import sys
input = sys.stdin.readline
from bisect import bisect_left
n = int(input())
s = list(input().rstrip())
ss = [97 - (ord(s[i]) - ord('a')) for i in range(n)]
INF = 10 ** 10
dp = [INF] * n
ans = []
for x in ss:
	pos = bisect_left(dp, x)
	ans.append(pos + 1)
	dp[pos] = x
print(max(ans))
print(*ans)


from bisect import bisect_left

def main():
	n = int(input().strip())
	s = input().strip()
	result = []
	fronts = []
	for c in s:
		i = bisect_left(fronts, -ord(c))
		if i >= len(fronts):
			fronts.append(-ord(c))
		else:
			fronts[i] = -ord(c)
		result.append(str(i + 1))
	print(len(fronts))
	print(' '.join(result))
main()


n = int(input())
s = str(input())
lit = ['Z'] * 26
wyn = ''
m = -1
for x in s:
	for y in range(26):
		if lit[y] <= x:
			wyn += str(y + 1) + ' '
			lit[y] = x
			if y + 1 >= m:
				m = y + 1
			break
print(m)
print(wyn)


def main():
	n = int(input())
	s = input()
	lst = ['a'] * n
	ans = []
	m = 0
	for i in range(n):
		for j in range(n):
			if lst[j] <= s[i]:
				lst[j] = s[i]
				ans.append(j + 1)
				m = max(m, j + 1)
				break
	print(m)
	print(*ans)
main()


n = int(input())
s = input()
rama = []
for i in range(n):
	rama.append(ord(s[i]) - 96)
visit = [1 for i in range(27)]
a = []
maxi = 0
for i in range(n):
	p = visit[rama[i]]
	a.append(p)
	maxi = max(maxi, p)
	for j in range(rama[i]):
		visit[j] = max(visit[j], p + 1)
print(maxi)
for i in a:
	print(i, end=' ')


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
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 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 SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(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)
MOD = 10 ** 9 + 7

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
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10)]
pp = [0] * 10

def SieveOfEratosthenes(n=10):
	p = 2
	c = 0
	while p * p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				pp[i] += 1
				prime[i] = False
		p += 1

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

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
n = int(input())
s = input()
curr = [''] * 100
m = 1
res = []
for i in range(n):
	for j in range(100):
		if s[i] >= curr[j]:
			curr[j] = s[i]
			res.append(j + 1)
			break
print(max(res))
print(*res)


n = int(input())
A = list(str(input()))
A = [ord(c) - ord('a') for c in A]
B = [10 ** 18]
ans = [-1] * n
import bisect
for i in reversed(range(n)):
	a = A[i]
	j = bisect.bisect_left(B, a)
	ans[i] = j + 1
	if 0 <= j < len(B):
		B[j] = a
	else:
		B.append(a)
print(len(B))
print(*ans)


import sys
input = sys.stdin.readline
n = int(input())
s = list(input().rstrip())
t = [ord(i) - 97 for i in s]
x = [[0] for _ in range(26)]
c = []
for i in t:
	for j in range(26):
		if x[j][-1] <= i:
			x[j].append(i)
			c.append(j + 1)
			break
res = max(c)
print(res)
print(*c)


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

def ceil(tails, L, R, key):
	while L + 1 < R:
		m = (L + R) // 2
		if key < tails[m]:
			L = m
		else:
			R = m
	return R

def LIS(a, n):
	tails = [0] * (n + 1)
	tails[0] = a[0]
	seq_len = 1
	for i in range(1, n):
		if a[i] > tails[0]:
			tails[0] = a[i]
			ans.append(1)
		elif a[i] < tails[seq_len - 1]:
			tails[seq_len] = a[i]
			seq_len += 1
			ans.append(seq_len)
		else:
			pos = ceil(tails, -1, seq_len - 1, a[i])
			tails[pos] = a[i]
			ans.append(pos + 1)
	return seq_len
n = int(input())
s = input()
ans = [1]
res = LIS(s, n)
print(res)
print(*ans)


from math import *
n = int(input())
s = input()
pre = [0 for i in range(n)]
pre[0] = 1
prev = s[0]
lst = [-1 for i in range(26)]
lst[0] = s[0]
ct = 1
for i in range(1, n):
	for j in range(26):
		if lst[j] == -1 or lst[j] <= s[i]:
			lst[j] = s[i]
			pre[i] = j + 1
			ct = max(ct, j + 1)
			break
print(ct)
for i in pre:
	print(i, end=' ')


import sys
input = sys.stdin.readline

class SegmentTree:

	def __init__(self, a):
		self.op = lambda a, b: max(a, b)
		self.e = 0
		self.n = len(a)
		self.lv = (self.n - 1).bit_length()
		self.size = 2 ** self.lv
		self.data = [self.e] * (2 * self.size - 1)
		self._check = lambda x, acc: acc >= x
		self._acc = self.e
		self.initialize(a)

	def initialize(self, a):
		for i in range(self.n):
			self.data[self.size + i - 1] = a[i]
		for i in range(self.size - 2, -1, -1):
			self.data[i] = self.op(self.data[i * 2 + 1], self.data[i * 2 + 2])

	def update(self, k, x):
		k += self.size - 1
		self.data[k] = x
		while k > 0:
			k = (k - 1) // 2
			self.data[k] = self.op(self.data[2 * k + 1], self.data[2 * k + 2])

	def fold(self, l, r):
		L = l + self.size
		R = r + self.size
		s = self.e
		while L < R:
			if R & 1:
				R -= 1
				s = self.op(s, self.data[R - 1])
			if L & 1:
				s = self.op(s, self.data[L - 1])
				L += 1
			L >>= 1
			R >>= 1
		return s

	def _bisect_forward(self, x, start, k):
		if k >= self.size - 1:
			self._acc = self.op(self._acc, self.data[k])
			if self._check(x, self._acc):
				return k - (self.size - 1)
			else:
				return -1
		width = 2 ** (self.lv - (k + 1).bit_length() + 1)
		mid = (k + 1) * width + width // 2 - self.size
		if mid <= start:
			return self._bisect_forward(x, start, 2 * k + 2)
		tmp_acc = self.op(self._acc, self.data[k])
		if start <= mid - width // 2 and (not self._check(x, tmp_acc)):
			self._acc = tmp_acc
			return -1
		vl = self._bisect_forward(x, start, 2 * k + 1)
		if vl != -1:
			return vl
		return self._bisect_forward(x, start, 2 * k + 2)

	def bisect_forward(self, x, start=None):
		if start:
			ret = self._bisect_forward(x, start, 0)
		else:
			ret = self._bisect_forward(x, 0, 0)
		self._acc = self.e
		return ret

	def _bisect_backward(self, x, start, k):
		if k >= self.size - 1:
			self._acc = self.op(self._acc, self.data[k])
			if self._check(x, self._acc):
				return k - (self.size - 1)
			else:
				return -1
		width = 2 ** (self.lv - (k + 1).bit_length() + 1)
		mid = (k + 1) * width + width // 2 - self.size
		if mid >= start:
			return self._bisect_backward(x, start, 2 * k + 1)
		tmp_acc = self.op(self._acc, self.data[k])
		if start > mid + width // 2 and (not self._check(x, tmp_acc)):
			self._acc = tmp_acc
			return -1
		vl = self._bisect_backward(x, start, 2 * k + 2)
		if vl != -1:
			return vl
		return self._bisect_backward(x, start, 2 * k + 1)

	def bisect_backward(self, x, start=None):
		if start:
			ret = self._bisect_backward(x, start, 0)
		else:
			ret = self._bisect_backward(x, self.n, 0)
		self._acc = self.e
		return ret
n = int(input())
s = input().rstrip()
array = [0] * n
ST = SegmentTree(array)
event = []
for (i, ch) in enumerate(s):
	event.append((ch, i))
event.sort(reverse=True)
ans = [0] * n
for (ch, index) in event:
	val = ST.fold(0, index) + 1
	ans[index] = val
	ST.update(index, val)
print(max(ans))
print(*ans)


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

def binsearch(arr, left, right, x):
	l = left
	r = right + 1
	while l < r:
		mid = (l + r) // 2
		if arr[mid][-1] > x:
			l = mid + 1
		else:
			r = mid
	return l
n = int(input())
s = input().rstrip()
arr = []
for c in s:
	arr.append(c)
arr.sort()
ind = dict()
for i in range(n):
	if arr[i] not in ind:
		ind[arr[i]] = i
move = []
for i in range(n):
	temp = s[i]
	move.append(ind[temp])
	ind[temp] += 1
piles = []
for i in range(n):
	ind = binsearch(piles, 0, len(piles) - 1, move[i])
	if ind >= len(piles):
		piles.append([move[i]])
	else:
		piles[ind].append(move[i])
colors = [-1] * n
for i in range(len(piles)):
	for j in range(len(piles[i])):
		colors[piles[i][j]] = i
ans = [-1] * n
for i in range(n):
	ans[i] = colors[move[i]]
print(len(piles))
for num in ans:
	print(num + 1, end=' ')
print()


n = int(input())
it = list(input())
it = [ord(i) - 97 for i in it]
lds = [1]
pre = [0 for i in range(26)]
pre[it[0]] = 1
for i in range(1, n):
	lds.append(1)
	pre[it[i]] = max(pre[it[i]], 1)
	for j in range(it[i] + 1, 26):
		pre[it[i]] = max(pre[it[i]], pre[j] + 1)
	lds[-1] = pre[it[i]]
print(max(lds))
print(*lds)


def binSearch(a, n):
	(i, j) = (0, len(a) - 1)
	while i != j:
		if (j - i) % 2 == 1:
			if a[i + (j - i) // 2] > n:
				i = i + (j - i) // 2 + 1
			else:
				j = i + (j - i) // 2
		elif a[i + (j - i) // 2] > n:
			i = i + (j - i) // 2
		else:
			j = i + (j - i) // 2
	return i
input()
k = ['a'] * 26
ans = ''
maxColor = 1
for symb in input():
	i = binSearch(k, symb)
	ans += str(i + 1) + ' '
	if i + 1 > maxColor:
		maxColor = i + 1
	k[i] = symb
print(maxColor)
print(ans)


n = int(input())
s = input()
dp = [0 for i in range(30)]
ans = [1 for i in range(n)]
for i in range(n):
	tmp = ord(s[i]) - ord('a')
	for j in range(tmp + 1, 26):
		ans[i] = max(ans[i], dp[j] + 1)
	dp[tmp] = ans[i]
print(max(ans))
for i in ans:
	print(i, end=' ')


n = int(input())
s = input()
col = [1] * n
prev = [0] * 27
for i in range(n):
	code = ord(s[i]) - ord('a')
	col[i] = max(prev[code + 1:]) + 1
	prev[code] = col[i]
print(max(col))
print(*col)


class SegmentTree:

	def __init__(self, n, op, e):
		self.n = n
		self.op = op
		self.e = e
		self.size = 2 ** (n - 1).bit_length()
		self.node = [self.e] * (2 * self.size)

	def built(self, array):
		for i in range(self.n):
			self.node[self.size + i] = array[i]
		for i in range(self.size - 1, 0, -1):
			self.node[i] = self.op(self.data[i << 1], self.data[(i << 1) + 1])

	def update(self, i, val):
		i += self.size
		self.node[i] = val
		while i > 1:
			i >>= 1
			self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])

	def get_val(self, l, r):
		(l, r) = (l + self.size, r + self.size)
		res = self.e
		while l < r:
			if l & 1:
				res = self.op(self.node[l], res)
				l += 1
			if r & 1:
				r -= 1
				res = self.op(self.node[r], res)
			(l, r) = (l >> 1, r >> 1)
		return res
import sys
input = sys.stdin.readline
n = int(input())
s = input()
st = SegmentTree(n, max, 0)
s = sorted([(s[i], i) for i in range(n)])[::-1]
cnt = 0
for (char, i) in s:
	min_ = st.get_val(0, i)
	st.update(i, min_ + 1)
	cnt = max(cnt, min_ + 1)
print(cnt)
print(*st.node[st.size:st.size + n])


import sys
input = lambda : sys.stdin.readline().strip()
n = int(input())
s = input()
color = [0 for i in range(n)]
counter = [0 for i in range(26)]
for i in range(n):
	color[i] = max(counter[ord(s[i]) - ord('a') + 1:], default=0) + 1
	counter[ord(s[i]) - ord('a')] = max(counter[ord(s[i]) - ord('a')], color[i])
print(max(color))
print(*color)


INF = 10 ** 10

def main():
	print = out.append
	n = get_int()
	st = list(input())
	li = [0] * 26
	res = [0] * n
	for (i, ele) in reversed(list(enumerate(st))):
		cnt = 0
		for j in range(ord(ele) - ord('a')):
			cnt = max(li[j], cnt)
		res[i] = cnt + 1
		li[ord(ele) - ord('a')] = cnt + 1
	print(max(res))
	print(' '.join(map(str, res)))
import sys
from collections import defaultdict, Counter
from bisect import bisect_left, bisect_right
import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda : int(input())
get_list = lambda : list(map(int, input().split()))
main()
print(*out, sep='\n')


input()
x = ['a']
d = []
for c in input():
	i = 0
	while c < x[i]:
		i += 1
		if i == len(x):
			x.append(c)
	x[i] = c
	d.append(i + 1)
print(max(d), *d)


from sys import stdin, stdout
from math import pow
from os import path
if path.exists('inp.txt'):
	stdin = open('inp.txt', 'r')
d = [1 for i in range(26)]
q = []
color = 1
n = int(stdin.readline())
s = stdin.readline()
cur = 'a'

def check(x):
	ans = 0
	for i in range(x + 1, 26):
		ans = max(d[i], ans)
	return ans
for i in range(n):
	if s[i] < cur:
		d[ord(s[i]) - ord('a')] = check(ord(s[i]) - ord('a')) + 1
		color = max(color, d[ord(s[i]) - ord('a')])
	else:
		cur = s[i]
	q.append(d[ord(s[i]) - ord('a')])
print(color)
for v in q:
	print(v, end=' ')


n = int(input())
s = input()
ans = 1
d = ''
arr = ['a']
for i in range(n):
	if s[i] < arr[-1]:
		d += str(len(arr) + 1) + ' '
		arr.append(s[i])
	else:
		for j in range(len(arr)):
			if s[i] >= arr[j]:
				d += str(j + 1) + ' '
				arr[j] = s[i]
				break
print(len(arr))
print(d)


from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin

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 lsi():
	x = list(stdin.readline())
	x.pop()
	return x

def si():
	return stdin.readline()

def sieve(x):
	a = [True] * (x + 1)
	sq = floor(sqrt(x))
	for i in range(3, sq + 1, 2):
		if a[i]:
			for j in range(i * i, x + 1, i):
				a[j] = False
	if x > 1:
		p = [2]
	else:
		p = []
	for i in range(3, x + 1, 2):
		if a[i]:
			p.append(i)
	return p
res = ['YES', 'NO']
p = [set() for _ in range(26)]
n = ii()
ans = [0] * n
a = lsi()
for i in range(n):
	ans[i] = len(p[ord(a[i]) - 97])
	for x in range(97, ord(a[i])):
		p[x - 97].add(ans[i])
print(max(ans) + 1)
print(*[i + 1 for i in ans])


n = int(input())
s = input()
(c, res) = (['0'] * 26, [''] * n)
for i in range(n):
	for j in range(26):
		if s[i] >= c[j]:
			res[i] = str(j + 1)
			c[j] = s[i]
			break
print(26 - c.count('0'))
print(' '.join(res))


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, S):
	indices = [[0]]
	for (i, x) in enumerate(S[1:], 1):
		for l in indices:
			if S[l[-1]] <= x:
				l.append(i)
				break
		else:
			indices.append([i])
	ans = [None for i in range(N)]
	for (color, l) in enumerate(indices):
		for i in l:
			ans[i] = color
	possible = str(len(indices))
	return possible + '\n' + ' '.join((str(x + 1) for x in ans))
	if len(indices) <= 2:
		return 'YES\n' + ''.join(map(str, ans))
	else:
		return 'NO'
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
S = input().decode().rstrip()
ans = solve(N, S)
print(ans)


n = int(input())
s = input()
p = [-1] * n
dd = [0] * 26
p[0] = 1
dd[ord(s[0]) - 97] = 1
for i in range(1, n):
	f = 0
	mxj = 0
	for j in range(26):
		if dd[j] != 0 and j > ord(s[i]) - 97:
			f = 1
			mxj = max(mxj, dd[j])
	p[i] = mxj + 1
	dd[ord(s[i]) - 97] = p[i]
print(max(p))
for i in p:
	print(i, end=' ')


n = int(input())
s = input()
alpha = [0] * 26
col = []
for i in range(0, len(s)):
	c = 0
	for j in range(ord(s[i]) - 97 + 1, 26):
		c = max(c, alpha[j])
	col.append(c + 1)
	alpha[ord(s[i]) - 97] = c + 1
print(max(col))
print(*col)


n = int(input())
s = input()
arr = ['a' for i in range(n)]
l = []
for i in s:
	for j in range(n):
		if i >= arr[j]:
			arr[j] = i
			l.append(j + 1)
			break
print(max(l))
print(*l)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
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))
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()
from random import randint
from collections import defaultdict, deque

class Graph(object):

	def __init__(self, dic):
		self.dict = dic
		self.vertex = set()

	def addedge(self, a, b):
		if self.dict[a] == []:
			self.vertex.add(a)
		if b != None:
			self.dict[a].append(b)

	def con_com_util(self, i, unvisited, count, comp):
		for j in self.dict[i]:
			if j in unvisited:
				unvisited.remove(j)
				comp[count].append(j)
				comp = self.con_com_util(j, unvisited, count, comp)
		return comp

	def conn_components(self):
		unvisited = self.vertex.copy()
		count = 0
		comp = defaultdict(list)
		while unvisited:
			i = unvisited.pop()
			comp[count].append(i)
			comp = self.con_com_util(i, unvisited, count, comp)
			count += 1
		return (count, comp)

def countSetBits(n):
	count = 0
	while n:
		n &= n - 1
		count += 1
	return count

def g():
	return -1
from math import ceil

def solve():
	n = int(inp())
	s = inp()
	ar = [s[0]]
	ans = [1]
	for i in range(1, n):
		for j in range(len(ar) + 1):
			if j == len(ar):
				ar.append(s[i])
				ans.append(j + 1)
				break
			if s[i] >= ar[j]:
				ar[j] = s[i]
				ans.append(j + 1)
				break
	print(len(ar))
	for i in ans:
		print(i, end=' ')
solve()


n = int(input())
s = input()
colors = ['_'] * 26
ans = [''] * n
idx = 0
for c in s:
	for i in range(26):
		if c >= colors[i]:
			ans[idx] = str(i + 1)
			colors[i] = c
			break
	idx += 1
print(26 - colors.count('_'))
print(' '.join(ans))


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline

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 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').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
n = val()
s = st()
l = [-(ord(i) - ord('a')) for i in s]
dp = [float('inf')] * n
ind = 0
ans = []
for i in l:
	ind = bl(dp, i)
	ans.append(ind + 1)
	dp[ind] = i
print(max(ans), *ans, sep='\n')


t = 1
while t != 0:
	t -= 1
	n = int(input())
	s = input()
	aux = 'abcdefghijklmnopqrstuvwxyz'
	maxi = [0 for _ in range(26)]
	dp = [1 for _ in range(n)]
	for i in range(n):
		for j in range(aux.find(s[i]) + 1, 26):
			dp[i] = max(dp[i], maxi[j] + 1)
		maxi[aux.find(s[i])] = dp[i]
	st = set(dp)
	print(len(st))
	print(*dp)


n = int(input())
s = input()
kol = [-1] * n
cur = 1
ind = 0
while ind < n:
	if kol[ind] != -1:
		ind += 1
	else:
		kol[ind] = cur
		best = s[ind]
		for i in range(ind + 1, n):
			if kol[i] != -1:
				continue
			elif s[i] >= best:
				kol[i] = cur
				best = s[i]
		ind += 1
		cur += 1
print(max(kol))
for i in range(n):
	print(kol[i], end=' ')


n = int(input())
s = list(map(ord, input()))
b = [0 for i in range(26)]
ans = []
for i in s:
	for j in range(26):
		if b[j] <= i:
			b[j] = i
			ans.append(j + 1)
			break
print(26 - b.count(0))
print(*ans)


def main():
	n = int(input())
	s = input()
	dp = []
	ans = []
	for i in range(n - 1, -1, -1):
		letters = [0] * 26
		if dp:
			for j in range(26):
				letters[j] = dp[-1][j]
			for j in range(ord(s[i]) - ord('a')):
				letters[ord(s[i]) - ord('a')] = max(letters[ord(s[i]) - ord('a')], dp[-1][j] + 1)
			letters[ord(s[i]) - ord('a')] = max(letters[ord(s[i]) - ord('a')], 1)
		else:
			letters[ord(s[i]) - ord('a')] = 1
		ans.append(letters[ord(s[i]) - ord('a')])
		dp.append(letters)
	ans.reverse()
	max_val = max(dp[-1])
	print(max_val)
	for i in ans:
		print(i, end=' ')
main()


from math import *
import re
n = int(input())
a1 = map(ord, list(input()))
a = []
for c in a1:
	a += [c - ord('a')]
(d, md) = ([1] * n, [0] * 26)
for i in range(n):
	j = 25
	while j > a[i]:
		d[i] = max(d[i], md[j] + 1)
		j -= 1
	md[a[i]] = max(md[a[i]], d[i])
print(max(md))
print(*d)