The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.

Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions:



 For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$;

 The number of zeroes in $t$ is the maximum possible.

A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$.

If there are multiple substrings which satisfy the conditions, output any.


-----Input-----

The first line contains a binary string of length not more than $2\: 000$.


-----Output-----

Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.


-----Examples-----
Input
110

Output
010

Input
010

Output
010

Input
0001111

Output
0000000

Input
0111001100111011101000

Output
0011001100001011101000



-----Note-----

In the first example: 

 For the substrings of the length $1$ the length of the longest non-decreasing subsequnce is $1$;  For $l = 1, r = 2$ the longest non-decreasing subsequnce of the substring $s_{1}s_{2}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{2}$ is $01$;  For $l = 1, r = 3$ the longest non-decreasing subsequnce of the substring $s_{1}s_{3}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{3}$ is $00$;  For $l = 2, r = 3$ the longest non-decreasing subsequnce of the substring $s_{2}s_{3}$ is $1$ and the longest non-decreasing subsequnce of the substring $t_{2}t_{3}$ is $1$; 

The second example is similar to the first one.

Source: codeforces | Difficulty: HARD
Tags: String algorithms

Complete search

Greedy algorithms


Solutions:
S = list(map(int, input().strip()))
N = len(S)
stack = []
for i in range(N):
	s = S[i]
	if s == 0 and stack and (stack[-1][0] == 1):
		stack.pop()
	else:
		stack.append((s, i))
T = S[:]
for i in tuple(map(list, zip(*stack)))[1]:
	T[i] = 0
print(''.join(map(str, T)))


a = input() + '1'
n = len(a) - 1
s = [0] * (n + 1)
for q in range(n - 1, -1, -1):
	s[q] = s[q + 1]
	if a[q] == '1':
		s[q] += 1
d = [0] * (n + 1)
for q in range(n - 1, -1, -1):
	d[q] = max(s[q], d[q + 1])
	if a[q] == '0':
		d[q] = max(d[q], d[q + 1] + 1)
t = []
for q in range(n):
	if a[q] == '0':
		t.append('0')
	elif d[q] == d[q + 1] + 1:
		t.append('0')
	else:
		t.append('1')
print(''.join(t))


pp = input()
if len(pp) == 1:
	print('0')
	return
z = 1 if pp[0] == '0' else 0
zc = [z]
l = 1
lndl = [l]
for p in pp[1:]:
	l = max(z + 1, l + (1 if p == '1' else 0))
	z += 1 if p == '0' else 0
	lndl.append(l)
	zc.append(z)
lnda = lndl[-1]
o = 1 if pp[-1] == '1' else 0
oc = [o]
l = 1
lndr = [l]
for p in reversed(pp[:-1]):
	l = max(o + 1, l + (1 if p == '0' else 0))
	o += 1 if p == '1' else 0
	lndr.append(l)
	oc.append(o)
oc.reverse()
lndr.reverse()
qq = []
ez = 0
if pp[0] == '1':
	if max(oc[1], lndr[1] + 1) != lnda:
		qq.append('1')
	else:
		qq.append('0')
		ez += 1
else:
	qq.append('0')
for (p, l, o, z, r) in zip(pp[1:-1], lndl, oc[2:], zc, lndr[2:]):
	if p == '1':
		if max(l + o, z + ez + 1 + r) != lnda:
			qq.append('1')
		else:
			qq.append('0')
			ez += 1
	else:
		qq.append('0')
qq.append('0')
print(''.join(qq))


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 = 0
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][0] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
s = input()
n = len(s)
a = [int(i) for i in s]
one = []
zero = []
for i in range(n):
	if a[i] == 0:
		zero.append(i)
	else:
		one.append(i)
j = len(zero) - 1
for i in one[::-1]:
	if j >= 0 and zero[j] > i:
		j -= 1
	else:
		a[i] = 0
print(*a, sep='')


s = input()
ans = ['0' for i in range(len(s))]
st = []
for i in range(len(s)):
	if s[i] == '0':
		if len(st):
			ans[st.pop()] = '1'
	else:
		st.append(i)
print(''.join(ans))


import sys
input = sys.stdin.readline

def solve():
	i = 0
	s = list(input().strip())
	st = []
	for c in s:
		if c == '1':
			st.append(i)
		elif len(st) > 0:
			st.pop()
		i += 1
	for i in st:
		s[i] = '0'
	print(''.join(s))
solve()


s = input()
res = ['0'] * len(s)
min_dif = 0
length = len(s)
for i in range(length):
	if s[length - i - 1] == '0':
		min_dif = min([-1, min_dif - 1])
	else:
		if min_dif < 0:
			res[length - i - 1] = '1'
		min_dif = min([1, min_dif + 1])
print(''.join(res))


s = input()
s = [*s]
c = m = 0
for i in range(len(s) - 1, -1, -1):
	c += -1 if s[i] == '0' else 1
	if c > m:
		s[i] = '0'
		m = c
print(''.join(s))


a = list(map(int, input()))
w = [0] * len(a)
q = []
for i in range(len(a)):
	if a[i] == 1:
		q.append(i)
	elif len(q) > 0:
		qw = q.pop()
		w[qw] = 1
print(*w, sep='')


import sys
s = list(input())
l = len(s)
sun = 0
for i in range(l - 1, -1, -1):
	if s[i] == '0':
		sun += 1
	elif s[i] == '1' and sun:
		sun -= 1
	else:
		s[i] = '0'
print(''.join(s))


s = list(map(int, input()))
ans = []
cnt = 0
if s[0] == 1:
	cnt += 1
else:
	ans.append('0')
for i in range(1, len(s)):
	if s[i] == 0 and s[i - 1] == 0:
		ans.append('0')
	elif s[i] == 1:
		cnt += 1
	else:
		maba = 0
		b = 0
		for x in range(i, len(s)):
			if s[x] == 1:
				b -= 1
			else:
				b += 1
			maba = max(maba, b)
		maba = min(maba, cnt)
		for _ in range(cnt - maba):
			ans.append('0')
		for _ in range(maba):
			ans.append('1')
		cnt = 0
		ans.append('0')
for _ in range(len(s) - len(ans)):
	ans.append('0')
print(''.join(ans))


def naiveSolve():
	return

def getLongestIncreasingLength(s):
	n = len(s)
	arr = [int(x) for x in s]
	ans = 0
	for mask in range(1 << n):
		arr2 = []
		for i in range(n):
			if mask & 1 << i > 0:
				arr2.append(arr[i])
		arr3 = sorted(arr2)
		if arr2 == arr3:
			ans = max(ans, len(arr2))
	return ans

def main():
	s = input()
	arr = [int(x) for x in s]
	n = len(arr)
	pc0 = [0] * n
	pc1 = [0] * n
	for i in range(n):
		if arr[i] == 0:
			pc0[i] += 1
		else:
			pc1[i] += 1
	for i in range(1, n):
		pc0[i] += pc0[i - 1]
		pc1[i] += pc1[i - 1]

	def q0(l, r):
		if l == 0:
			return pc0[r]
		else:
			return pc0[r] - pc0[l - 1]

	def q1(l, r):
		if l == 0:
			return pc1[r]
		else:
			return pc1[r] - pc1[l - 1]
	for i in range(n):
		if arr[i] == 1:
			ok = True
			for r in range(i, n):
				if q1(i, r) <= q0(i, r):
					ok = False
					break
			if ok:
				arr[i] = 0
	ans = ''.join([str(x) for x in arr])
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(r):
	print('? {}'.format(r))
	sys.stdout.flush()
	return readIntArr()

def answerInteractive(adj, n):
	print('!')
	for u in range(1, n + 1):
		for v in adj[u]:
			if v > u:
				print('{} {}'.format(u, v))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
from math import gcd, floor, ceil
for _abc in range(1):
	main()


S = input()
N = len(S)
p = q = 0
prv = S[0]
c = 0
C = []
if S[0] == '1':
	C.append(0)
for ch in S:
	if ch != prv:
		C.append(c)
		c = 1
		prv = ch
	else:
		c += 1
C.append(c)
ans = []
r = 0
L = len(C)
for i in range(L - 1, -1, -1):
	c = C[i]
	if i % 2:
		r += c
		if i != L - 1:
			m = max(min(c - 1, r), 0)
		else:
			m = max(min(c, r), 0)
		if m:
			r -= m
			ans.append('0' * m + '1' * (c - m))
		else:
			ans.append('1' * c)
	else:
		r -= c
		ans.append('0' * c)
ans.reverse()
print(*ans, sep='')


data = [int(i) for i in input()]
n = len(data)
minval = [0] * n
minval[-1] = 2 * data[-1] - 1
for i in range(n - 2, -1, -1):
	if data[i] == 1:
		minval[i] = min(1, minval[i + 1] + 1)
	else:
		minval[i] = min(-1, minval[i + 1] - 1)
ans = [i for i in data]
for i in range(n - 1, -1, -1):
	if minval[i] == 1:
		ans[i] = 0
ans2 = [str(i) for i in ans]
print(''.join(ans2))


s = list(map(int, input()))
stack = []
for i in range(len(s)):
	if s[i] == 1:
		stack.append(i)
	elif len(stack) != 0:
		stack.pop()
for i in stack:
	s[i] = 0
s = list(map(str, s))
print(''.join(s))


import os
import sys
from math import *
from collections import *
from bisect 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 = 998244353
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

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()]
s = [int(i) for i in input()]
n = len(s)
ans = [0] * n
have = 0
for i in range(n - 1, -1, -1):
	if not s[i]:
		have += 1
	elif have:
		have -= 1
		ans[i] = 1
print(*ans, sep='')


s = input()
n = len(s)
b = [0] * n
l = []
m = []
j = 0
for i in s:
	if len(l) == 0:
		l.append(i)
		m.append(j)
	elif l[-1] == '1' and i == '0':
		l.pop()
		b[m.pop()] = 1
	else:
		l.append(i)
		m.append(j)
	j += 1
print(*b, sep='')


from sys import stdin
s = stdin.readline().strip()
dp = [0 for i in range(len(s) + 2)]
ons = [0 for i in range(len(s) + 2)]
zs = [0 for i in range(len(s) + 2)]
for i in range(len(s) - 1, -1, -1):
	if s[i] == '1':
		ons[i] += 1
	if i != len(s) - 1:
		ons[i] += ons[i + 1]
z = 0
for i in range(len(s) - 1, -1, -1):
	if s[i] == '1':
		dp[i] = max(1 + ons[i + 1], z)
	else:
		dp[i] = max(dp[i + 1] + 1, 1 + ons[i + 1])
		z = dp[i]
	zs[i] = z
ans = ''
for i in range(len(s)):
	if s[i] == '1':
		x = dp[i]
		y = 1 + dp[i + 1]
		if x == y:
			ans += '0'
		else:
			ans += '1'
	else:
		ans += '0'
print(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')
from math import factorial
from collections import Counter, defaultdict, deque
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')

def main():
	s = list(input())
	le = len(s)
	rec = []
	for i in range(le):
		if rec and s[i] == '0' and (s[rec[-1]] == '1'):
			rec.pop()
		else:
			rec.append(i)
	for i in rec:
		s[i] = '0'
	print(''.join(s))
main()


s = input()
pre = [0 for i in range(111111)]
suf = [0 for i in range(111111)]
lens = len(s)
index = 0
for i in s:
	index += 1
	t = 0
	if i == '0':
		t = 1
	else:
		t = -1
	pre[index] = min(pre[index - 1] + t, t)
index = lens + 1
for i in reversed(s):
	index -= 1
	t = 0
	if i == '0':
		t = 1
	else:
		t = -1
	suf[index] = max(suf[index + 1] + t, t)
x = 0
for (index, i) in enumerate(s):
	if i == '0':
		print(i, end='')
		pre[index + 1] = min(pre[index] + 1, 1)
	elif pre[index] >= 0 and suf[index + 2] <= 0:
		print('0', end='')
		pre[index + 1] = min(pre[index] + 1, 1)
	else:
		print('1', end='')
		pre[index + 1] = min(pre[index] - 1, -1)


inn = lambda : int(input())
inl = lambda : list(map(int, input().split()))
inm = lambda : map(int, input().split())
DBG = True and False

def ddprint(x):
	if DBG:
		print(x)
s = input().strip()
n = len(s)
ones = []
stk = []
for i in range(n):
	if len(stk) > 0 and stk[-1][0] == '1' and (s[i] == '0'):
		ones.append(stk[-1][1])
		stk.pop()
	else:
		stk.append((s[i], i))
ones.sort()
ans = ''
cur = 0
for i in ones:
	for j in range(cur, i):
		ans += '0'
	ans += '1'
	cur = i + 1
for j in range(cur, n):
	ans += '0'
print(ans)


s = input()
s = list(s)
l = len(s) - 1
z = 0
for i in range(l, -1, -1):
	if s[i] == '0':
		z += 1
	elif z:
		z -= 1
	else:
		s[i] = '0'
s = ''.join(s)
print(s)


import sys
input = sys.stdin.readline
s = list(input().rstrip())
n = len(s)
c = m = 0
for i in range(n)[::-1]:
	c += -1 if s[i] == '0' else 1
	if c > m:
		s[i] = '0'
		c = m
print(''.join(s))


s = input()
ans = []
for i in range(0, len(s)):
	ans.append(s[i])
c0 = 0
c1 = 0
for i in range(len(ans) - 1, -1, -1):
	if ans[i] == '0':
		c0 += 1
	elif ans[i] == '1' and c1 >= c0:
		ans[i] = '0'
	else:
		c1 += 1
ans = ''.join(ans)
print(ans)


def main():
	import sys
	input = sys.stdin.readline
	s = [int(i) for i in input()[:-1]][::-1]
	n = len(s)
	dp = [[0] * n for _ in range(n)]
	for j in range(n):
		tmp = [0, 0]
		for i in range(j, n):
			if s[i] == 0:
				tmp[0] = max(tmp) + 1
				dp[j][i] = tmp[0]
			else:
				tmp[1] += 1
				dp[j][i] = tmp[1]
	t = ''
	dp2 = [[0] * n for _ in range(n)]
	tmp = [[0, 0] for _ in range(n)]
	for j in range(n):
		okay = 1
		prev = [0] * (j + 1)
		for i in range(j + 1):
			prev[i] = tmp[i][0]
			tmp[i][0] = max(tmp[i]) + 1
			dp2[i][j] = tmp[i][0]
			if dp2[i][j] != dp[i][j]:
				okay = 0
		if not okay:
			for i in range(j + 1):
				tmp[i][0] = prev[i]
				tmp[i][1] += 1
				dp2[i][j] = tmp[i][1]
			t += '1'
		else:
			t += '0'
	print(t[::-1])
	return 0
main()


s = input()
(a, b, c) = ([], [], [])
count = 0
for i in range(len(s) - 1, -1, -1):
	a.append(s[i])
for i in range(len(a)):
	if a[i] == '0':
		count += 1
		b.append('0')
	elif a[i] == '1' and count > 0:
		count -= 1
		b.append('1')
	elif a[i] == '1' and count == 0:
		b.append('0')
for i in range(len(b) - 1, -1, -1):
	c.append(b[i])
ans = ''.join(c)
print(ans)


line = input()
res = []
zer = 0
one = 0
for i in range(len(line)):
	ind = len(line) - 1 - i
	if line[ind] == '0':
		res.append('0')
		zer += 1
	else:
		if zer <= one:
			res.append('0')
			zer += 1
		else:
			res.append('1')
		one += 1
for i in range(len(res)):
	print(res[len(res) - 1 - i], end='')
print('\n', end='')


s = str(input().strip())
t = list(s[::-1])
cnt = 0
for (i, v) in enumerate(t):
	if v == '0':
		cnt += 1
	elif cnt:
		cnt -= 1
	else:
		t[i] = '0'
print(''.join(t[::-1]))


(v, t) = (0, '')
for c in input()[::-1]:
	if c < '1' or v:
		t += c
		v += 1 - (c < '1') * 2
	else:
		t += '0'
print(t[::-1])


st = input().rstrip()
a = []
for item in st:
	a.append(int(item))
a.reverse()
zero_count = 0
for (i, item) in enumerate(a):
	if item == 0:
		zero_count += 1
	elif zero_count > 0:
		zero_count -= 1
	else:
		a[i] = 0
a.reverse()
print(''.join([str(item) for item in a]))


s = list(map(int, input()))
ps = [0]
for i in s:
	if i == 0:
		ps.append(ps[-1] + 1)
	else:
		ps.append(ps[-1] - 1)
b = 0
maba = 0
sufmax = [-10 ** 9]
for i in range(len(ps) - 1, 0, -1):
	sufmax.append(max(sufmax[-1], ps[i]))
sufmax = sufmax[::-1]
ans = []
cnt = 0
if s[0] == 1:
	cnt += 1
else:
	ans.append('0')
for i in range(1, len(s)):
	if s[i] == 0 and s[i - 1] == 0:
		ans.append('0')
	elif s[i] == 1:
		cnt += 1
	else:
		maba = sufmax[i] - ps[i]
		maba = min(maba, cnt)
		for _ in range(cnt - maba):
			ans.append('0')
		for _ in range(maba):
			ans.append('1')
		cnt = 0
		ans.append('0')
for _ in range(len(s) - len(ans)):
	ans.append('0')
print(''.join(ans))


INF = 10 ** 10

def main():
	st = list(input())
	stk = []
	for (index, i) in enumerate(st):
		if i == '0' and len(stk) > 0 and (stk[-1][0] == '1'):
			stk.pop()
		else:
			stk.append([i, index])
	for li in stk:
		st[li[1]] = '0'
	print(''.join(st))
import sys
out = []
get_int = lambda : int(input())
get_list = lambda : list(map(int, input().split()))
main()
print(*out, sep='\n')


s = input()
t = ''
blockable_ones = 0
is_blockable = False
last_num = '1'
for i in range(1, len(s) + 1):
	num = s[-i]
	if num == '0':
		t += num
		blockable_ones += 1
		is_blockable = True
	elif blockable_ones > 0 and is_blockable:
		blockable_ones -= 1
		t += num
	else:
		t += '0'
	last_num = num
print(t[::-1])


s = input()[::-1]
ans = ''
c = 0
for i in s:
	if i == '0':
		ans += '0'
		c += 1
	elif c > 0:
		ans += '1'
		c -= 1
	else:
		ans += '0'
print(ans[::-1])


s = input()
ans = list(s)
n = len(s)
dp = [0] * n
i = 0
j = 1
while j < n:
	if s[i] == '1' and s[j] == '0':
		dp[i] = 1
		dp[j] = 1
		if i > 0:
			while dp[i] == 1 and i > 0:
				i -= 1
		j += 1
	else:
		j += 1
		i = j - 1
for i in range(n):
	if dp[i] == 0:
		ans[i] = '0'
print(''.join(ans))


s = str(input())
n = len(s)
ns = ['0' for i in range(n)]
st = []
for i in range(n):
	if s[i] == '0':
		if len(st):
			ns[st.pop()] = '1'
	else:
		st.append(i)
print(''.join(ns))


(v, ans) = (0, '')
for c in input()[::-1]:
	if c == '0' or v:
		ans += c
		v += 1 if c == '1' else -1
	else:
		ans += '0'
print(ans[::-1])


def naiveSolve():
	return
import math

class RMQMIN:

	def __init__(self, arr):
		self.arr = arr
		MAXN = len(arr)
		K = int(math.log2(MAXN)) + 1
		self.lookup = [[0 for _ in range(K + 1)] for __ in range(MAXN)]
		self.buildSparseTable()

	def buildSparseTable(self):
		n = len(self.arr)
		for i in range(0, n):
			self.lookup[i][0] = self.arr[i]
		j = 1
		while 1 << j <= n:
			i = 0
			while i + (1 << j) - 1 < n:
				if self.lookup[i][j - 1] < self.lookup[i + (1 << j - 1)][j - 1]:
					self.lookup[i][j] = self.lookup[i][j - 1]
				else:
					self.lookup[i][j] = self.lookup[i + (1 << j - 1)][j - 1]
				i += 1
			j += 1

	def query(self, L, R):
		j = int(math.log2(R - L + 1))
		if self.lookup[L][j] <= self.lookup[R - (1 << j) + 1][j]:
			return self.lookup[L][j]
		else:
			return self.lookup[R - (1 << j) + 1][j]

def main():
	s = input()
	arr = [int(x) for x in s]
	n = len(arr)
	pc0 = [0] * n
	pc1 = [0] * n
	for i in range(n):
		if arr[i] == 0:
			pc0[i] += 1
		else:
			pc1[i] += 1
	for i in range(1, n):
		pc0[i] += pc0[i - 1]
		pc1[i] += pc1[i - 1]

	def q0(l, r):
		if l == 0:
			return pc0[r]
		else:
			return pc0[r] - pc0[l - 1]

	def q1(l, r):
		if l == 0:
			return pc1[r]
		else:
			return pc1[r] - pc1[l - 1]
	rmqArr = [0] * n
	for r in range(n):
		rmqArr[r] = q1(0, r) - q0(0, r)
	rmq = RMQMIN(rmqArr)
	delta = 0
	for i in range(n):
		if arr[i] == 1:
			if rmq.query(i, n - 1) + delta > 0:
				arr[i] = 0
			delta -= 1
		else:
			delta += 1
	ans = ''.join([str(x) for x in arr])
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(r):
	print('? {}'.format(r))
	sys.stdout.flush()
	return readIntArr()

def answerInteractive(adj, n):
	print('!')
	for u in range(1, n + 1):
		for v in adj[u]:
			if v > u:
				print('{} {}'.format(u, v))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
from math import gcd, floor, ceil
for _abc in range(1):
	main()


s = input()
t = list(s)
stack = []
for i in range(len(s)):
	if t[i] == '1':
		stack.append(i)
	elif len(stack):
		stack.pop()
for i in range(len(stack)):
	t[stack[i]] = '0'
print(''.join(t))


s = input()[::-1]
count = 0
n = len(s)
s1 = ''
for i in range(n):
	if s[i] == '0':
		count += 1
		s1 += '0'
	elif count > 0:
		count -= 1
		s1 += '1'
	else:
		s1 += '0'
s1 = s1[::-1]
print(s1)


s = [int(x) for x in list(input())]
n = len(s)
b = [0] * n
counter = 0
for i in range(n - 1, -1, -1):
	if s[i] == 0:
		counter += 1
	elif counter > 0:
		counter -= 1
	else:
		s[i] = 0
arr = ''
for item in s:
	arr += str(item)
print(arr)


s = input()
n = len(s)
b = [0] * n
x = 1
l = []
for i in range(n):
	l.append(i)
while x == 1:
	x = 0
	for i in range(len(s) - 1):
		if s[i] == '1' and s[i + 1] == '0':
			x = 1
			b[int(l[i])] = 1
			l[i] = l[i + 1] = 1000000
	s = s.replace('10', '')
	l = list(set(l))
	if x == 1:
		l.remove(1000000)
print(*b, sep='')


def main():
	s = input()
	n = len(s)
	st = []
	flags = [False for i in range(n)]
	for i in range(n):
		if s[i] == '1':
			st.append(i)
		elif len(st) != 0:
			st.pop()
	for i in range(len(st)):
		flags[st[i]] = True
	for i in range(n):
		if flags[i] == True:
			print('0', end='')
		else:
			print(s[i], end='')
	print()
main()


import sys
import math

def main():
	s = input()
	q = []
	for i in range(len(s)):
		if s[i] == '1':
			q.append(i)
		elif len(q) > 0:
			q.pop()
	result = []
	q = set(q)
	for i in range(len(s)):
		if i in q:
			result.append('0')
		else:
			result.append(s[i])
	print(''.join(result))
main()


s = input()
n = len(s)
tot = 0
S = list(s)
for i in range(n - 1, -1, -1):
	if s[i] == '0':
		tot += 1
	elif tot:
		tot -= 1
	else:
		S[i] = '0'
print(''.join(S))


l = list(input())
ct = 0
n = len(l)
for i in range(n - 1, -1, -1):
	if l[i] == '0':
		ct += 1
	elif ct != 0:
		ct -= 1
	else:
		l[i] = '0'
print(''.join(l))


INF = 10 ** 10

def main():
	print = out.append
	st = list(input())
	stk = []
	for (index, i) in enumerate(st):
		if i == '0' and len(stk) > 0 and (stk[-1][0] == '1'):
			stk.pop()
		else:
			stk.append([i, index])
	for li in stk:
		st[li[1]] = '0'
	print(''.join(st))
import sys
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')


s = list(map(int, input()))
ans = [0] * len(s)
back = []
for (i, c) in enumerate(s):
	if c == 0:
		if back:
			ans[back.pop()] = 1
	else:
		back.append(i)
print(*ans, sep='')


(s, cnt) = (list(input()), 0)
for i in range(len(s) - 1, -1, -1):
	if s[i] == '0':
		cnt += 1
	elif cnt:
		cnt -= 1
	else:
		s[i] = '0'
print(''.join(s))


s = input()
n = len(s)
if n == 1:
	print(0)
elif n == 2:
	if s == '10':
		print('10')
	else:
		print('00')
else:
	s_lis = 0
	s_max = 0
	s_zero = 0
	t_zero = 0
	stack_01 = []
	t = []
	for i in range(n):
		t.append('0')
		t_zero += 1
		if s[i] == '0':
			s_zero += 1
		if i > 0 and s[i - 1:i + 1] == '10':
			t[i - 1] = '1'
			t_zero -= 1
			stack_01.append(i - 2)
		if s_max <= int(s[i]):
			s_lis += 1
			s_max = max(s_max, int(s[i]))
		if s_lis <= s_zero:
			s_lis = s_zero
			s_max = 0
		if s_lis < t_zero:
			while t[stack_01[-1]] == '1' or s[stack_01[-1]] == '0' or t[stack_01[-1] - 1] == '1':
				stack_01.pop()
			t[stack_01[-1]] = '1'
			t_zero -= 1
			stack_01[-1] -= 1
	print(*t, sep='')


s = input()
t = [0] * len(s)
stack = []
for i in range(len(s)):
	if s[i] == '1':
		stack.append(i)
	elif len(stack) > 0:
		pos = stack.pop()
		t[pos] = 1
print(''.join(map(str, t)))


import sys
sys.setrecursionlimit(10 ** 5 + 1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
given = input()[::-1]
zeros = 0
lens = len(given)
rets = ''
for i in range(lens):
	if given[i] == '0':
		zeros += 1
		rets += '0'
	elif zeros > 0:
		zeros -= 1
		rets += '1'
	else:
		rets += '0'
rets = rets[::-1]
print(rets)


s = input()
res = ['0'] * len(s)
stk = []
for i in range(len(s)):
	if s[i] == '0':
		if len(stk) > 0:
			res[stk[-1]] = '1'
			stk.pop()
	else:
		stk.append(i)
print(''.join(res))


a = input()
a = list(a)
l = []
for i in range(0, len(a)):
	l.append([a[i], i])
i = 1
while i < len(l):
	if l[i][0] == '0' and l[i - 1][0] == '1':
		l.pop(i)
		l.pop(i - 1)
		i -= 2
	if i == -1:
		i = 0
	i += 1
for i in range(0, len(l)):
	a[l[i][1]] = 0
print(*a, sep='')