Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types.

  speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type);  overtake is allowed: this sign means that after some car meets it, it can overtake any other car;  no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign);  no overtake allowed: some car can't overtake any other car after this sign. 

Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.

In the beginning of the ride overtake is allowed and there is no speed limit.

You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types:

  Polycarp changes the speed of his car to specified (this event comes with a positive integer number);  Polycarp's car overtakes the other car;  Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer);  Polycarp's car goes past the "overtake is allowed" sign;  Polycarp's car goes past the "no speed limit";  Polycarp's car goes past the "no overtake allowed"; 

It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).

After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?


-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 2·10^5) — number of events.

Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event.

An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit).

It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).


-----Output-----

Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.


-----Examples-----
Input
11
1 100
3 70
4
2
3 120
5
3 120
6
1 150
4
3 300

Output
2

Input
5
1 100
3 200
2
4
5

Output
0

Input
7
1 20
2
6
4
6
6
2

Output
2



-----Note-----

In the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120.

In the second example Polycarp didn't make any rule violation.

In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.

Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Data structures

Greedy algorithms
Skill types: Dynamic programming

Data structures

Greedy algorithms

Starter code:

Solutions:
from collections import deque
n = int(input())
speed_stack = deque()
over_take = 0
speed = 0
penalty = 0

def speed_check(penalty, x):
	while speed_stack and speed_stack[-1] < x:
		speed_stack.pop()
		penalty += 1
	return penalty
for i in range(n):
	update = [int(j) for j in input().split()]
	if update[0] == 1:
		speed = update[1]
		penalty = speed_check(penalty, speed)
	elif update[0] == 2:
		penalty += over_take
		over_take = 0
	elif update[0] == 3:
		speed_stack.append(update[1])
		penalty = speed_check(penalty, speed)
	elif update[0] == 4:
		over_take = 0
	elif update[0] == 5:
		speed_stack = deque()
	else:
		over_take += 1
print(penalty)


import math
from collections import Counter, defaultdict
from itertools import accumulate
R = lambda : map(int, input().split())
n = int(input())
spl = [math.inf]
ot_forbid = 0
sp = 0
res = 0
for i in range(n):
	arr = list(R())
	tp = arr[0]
	if tp == 1:
		sp = arr[1]
		while sp > spl[-1]:
			spl.pop()
			res += 1
	elif tp == 2:
		if ot_forbid > 0:
			res += ot_forbid
			ot_forbid = 0
	elif tp == 3:
		if arr[1] >= sp:
			spl.append(arr[1])
		else:
			res += 1
	elif tp == 4:
		ot_forbid = 0
	elif tp == 5:
		spl = [math.inf]
	else:
		ot_forbid += 1
print(res)


n = int(input())
overtaking = 0
answer = 0
speed = int(input()[2:])
limits = [300]
for _ in range(n - 1):
	action = input()
	if action[0] == '1':
		speed = int(action[2:])
		while limits[-1] < speed:
			answer += 1
			limits.pop()
	elif action[0] == '2':
		answer += overtaking
		overtaking = 0
	elif action[0] == '3':
		newlimit = int(action[2:])
		if speed > newlimit:
			answer += 1
		else:
			limits.append(newlimit)
	elif action[0] == '4':
		overtaking = 0
	elif action[0] == '5':
		limits = [300]
	elif action[0] == '6':
		overtaking += 1
print(answer)


n = int(input())
st = [0] * n
top = -1
curr_speed = 0
ans = 0
c = 0
while n > 0:
	n -= 1
	a = list(map(int, input().split()))
	if a[0] == 1:
		curr_speed = a[1]
		if top >= 0 and curr_speed > st[top]:
			while curr_speed > st[top] and top >= 0:
				top -= 1
				ans += 1
	if a[0] == 4:
		c = 0
	elif a[0] == 6:
		c += 1
	if a[0] == 5:
		top = -1
	if a[0] == 2:
		ans += c
		c = 0
	if a[0] == 3:
		if curr_speed > a[1]:
			ans += 1
		else:
			st[top + 1] = a[1]
			top += 1
print(ans)


from sys import stdin, stdout
from math import inf

def rint():
	return map(int, stdin.readline().split())
csp = 0
ov = 1
sign = []
ans = 0
spst = [inf]
ovst = [1]
n = int(input())
for i in range(n):
	sign = list(rint())
	if sign[0] == 1:
		csp = sign[1]
		while csp > spst[-1]:
			spst.pop()
			ans += 1
	if sign[0] == 2:
		while ovst[-1] == 0:
			ovst.pop()
			ans += 1
	if sign[0] == 3:
		if sign[1] >= csp:
			spst.append(sign[1])
		else:
			ans += 1
	if sign[0] == 4:
		ovst.append(1)
	if sign[0] == 5:
		spst.append(inf)
	if sign[0] == 6:
		ovst.append(0)
print(ans)


p = [1000000000.0]
d = k = v = 0
for i in range(int(input())):
	s = input()
	t = int(s[0])
	if t == 1:
		v = int(s[2:])
		while p[-1] < v:
			p.pop()
			k += 1
	if t == 2:
		(k, d) = (k + d, 0)
	if t == 3:
		u = int(s[2:])
		if v > u:
			k += 1
		else:
			p += [u]
	if t == 4:
		d = 0
	if t == 5:
		p = [1000000000.0]
	if t == 6:
		d += 1
print(k)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
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
avl = AvlTree()

class SegmentTree1:

	def __init__(self, data, default='z', 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 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
spe = 400
curspe = 0
w = [400]
over = 0
ans = 0
for ik in range(int(input())):
	a = list(map(int, input().split()))
	if a[0] == 4:
		over = 0
	elif a[0] == 6:
		over += 1
	elif a[0] == 2:
		if over >= 1:
			ans += over
			over = 0
	elif a[0] == 1:
		if a[1] > spe:
			while True:
				e = w.pop()
				spe = e
				if a[1] <= e:
					w.append(e)
					break
				else:
					ans += 1
		curspe = a[1]
	elif a[0] == 5:
		spe = 400
		w = [400]
	elif a[0] == 3:
		w.append(a[1])
		while True:
			e = w.pop()
			spe = e
			if curspe <= e:
				w.append(e)
				break
			else:
				ans += 1
print(ans)


MAX_SPEED = 300
n = int(input())
actions = [list(map(int, input().split())) for _ in range(n)]
speed = [0 for i in range(n)]
for i in range(n):
	if actions[i][0] == 1:
		lastSpeed = actions[i][1]
	speed[i] = lastSpeed
ignored = 0
overtook = False
maxSpeed = -1
for i in range(n - 1, -1, -1):
	maxSpeed = max(maxSpeed, speed[i])
	if actions[i][0] == 1:
		pass
	elif actions[i][0] == 2:
		overtook = True
	elif actions[i][0] == 3:
		if maxSpeed > actions[i][1]:
			ignored += 1
		else:
			maxSpeed = speed[i - 1]
	elif actions[i][0] == 4:
		overtook = False
	elif actions[i][0] == 5:
		maxSpeed = speed[i - 1]
	elif actions[i][0] == 6:
		if overtook:
			ignored += 1
print(ignored)


n = int(input())
no_overtake = 0
speedlimit = [float('inf')]
speed = 0
vio = 0
ot_ignored = False
for _ in range(n):
	cmd = input().split()
	if cmd[0] == '1':
		speed = int(cmd[1])
		while speed > speedlimit[-1]:
			vio += 1
			speedlimit.pop(-1)
	elif cmd[0] == '2':
		if no_overtake and (not ot_ignored):
			vio += no_overtake
			ot_ignored = True
	elif cmd[0] == '3':
		speedlimit.append(int(cmd[1]))
		if speed > speedlimit[-1]:
			vio += 1
			speedlimit.pop(-1)
	elif cmd[0] == '4':
		no_overtake = 0
		ot_ignored = False
	elif cmd[0] == '5':
		speedlimit = [float('inf')]
	elif cmd[0] == '6':
		if ot_ignored == 1:
			no_overtake = 0
		no_overtake += 1
		ot_ignored = False
print(vio)


n = int(input())
s = 0
ms = []
o = 1
z = 0
q = 0
for _ in range(n):
	a = list(map(int, input().split()))
	if a[0] == 1:
		s = a[1]
		while len(ms) > 0 and ms[-1] < s:
			z += 1
			ms.pop(-1)
	elif a[0] == 2:
		if o != 1:
			z += 1 - o
			o = 1
	elif a[0] == 3:
		ms.append(a[1])
		while len(ms) > 0 and ms[-1] < s:
			z += 1
			ms.pop(-1)
	elif a[0] == 4:
		o = 1
	elif a[0] == 5:
		ms = []
	elif a[0] == 6:
		o -= 1
print(z)


num = int(input())
slimit = []
ans = 0
last = 0
olimit = 1
for i in range(num):
	a = list(map(int, input().split()))
	if a[0] == 1:
		last = a[1]
		while len(slimit) > 0 and slimit[-1] < last:
			ans += 1
			slimit.pop(-1)
	elif a[0] == 2:
		if olimit != 1:
			ans += 1 - olimit
			olimit = 1
	elif a[0] == 3:
		slimit.append(a[1])
		while len(slimit) > 0 and slimit[-1] < last:
			ans += 1
			slimit.pop(-1)
	elif a[0] == 4:
		olimit = 1
	elif a[0] == 5:
		slimit = []
	elif a[0] == 6:
		olimit -= 1
print(ans)


import sys
n = int(sys.stdin.buffer.readline().decode('utf-8'))
inf = 10 ** 9
speed = 0
limit = [inf]
overtake = 1
ot_sign = 0
ans = 0
for _ in range(n):
	q = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
	if q[0] == 1:
		while limit[-1] < q[1]:
			ans += 1
			limit.pop()
		speed = q[1]
	elif q[0] == 2:
		if not overtake:
			ans += ot_sign
			ot_sign = 0
	elif q[0] == 3:
		if speed > q[1]:
			ans += 1
		else:
			limit.append(q[1])
	elif q[0] == 4:
		overtake = 1
		ot_sign = 0
	elif q[0] == 5:
		limit.clear()
		limit.append(inf)
	else:
		overtake = 0
		ot_sign += 1
print(ans)


(n, d) = (int(input()), [])
for i in range(n):
	d.append(tuple(map(int, input().split())))
(st, c) = ([], 0)
(ans, v) = (0, 0)
for i in d:
	if i[0] == 1:
		v = i[1]
		while len(st) != 0 and st[-1] < v:
			ans += 1
			st.pop()
	elif i[0] == 2:
		ans += c
		c = 0
	elif i[0] == 3:
		if v > i[1]:
			ans += 1
		else:
			st.append(i[1])
	elif i[0] == 4:
		c = 0
	elif i[0] == 5:
		st.clear()
	elif i[0] == 6:
		c += 1
print(ans)


class DrivingTest:
	car_speed = 0
	speed_limit = [0]
	overtake_allowed = [True]
	missed_signs = 0

	def __init__(self, test=False):
		if not test:
			event_count = int(input())
			for counter in range(event_count):
				event = input()
				self.handle_event(event)
			print(self.missed_signs)

	def handle_event(self, event):
		event = list(map(int, event.split()))
		event_type = event[0]
		if event_type == 1:
			self.set_car_speed(event[1])
		if event_type == 2:
			self.overtake_car()
		if event_type == 3:
			self.set_speed_limit(event[1])
		if event_type == 4:
			self.set_overtake_allowed(True)
		if event_type == 5:
			self.set_speed_limit(0)
		if event_type == 6:
			self.set_overtake_allowed(False)

	def set_car_speed(self, car_speed):
		self.car_speed = car_speed
		self.check_car_speed()

	def set_speed_limit(self, speed_limit):
		self.speed_limit.append(speed_limit)
		self.check_car_speed()

	def check_car_speed(self):
		latest_speed_limit = self.speed_limit[-1]
		while latest_speed_limit != 0 and latest_speed_limit < self.car_speed:
			self.missed_signs += 1
			self.speed_limit.pop()
			latest_speed_limit = self.speed_limit[-1]

	def set_overtake_allowed(self, overtake_allowed):
		self.overtake_allowed.append(overtake_allowed)

	def overtake_car(self):
		while not self.overtake_allowed[-1]:
			self.missed_signs += 1
			self.overtake_allowed.pop()

	def get_missed_signs(self):
		return self.missed_signs
DrivingTest()


import sys
n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
c2 = 0
speed = 0
c = 0
st = []
for i in a:
	if i[0] == 1:
		speed = i[1]
		while len(st) and st[-1] < speed:
			c += 1
			st.pop()
	elif i[0] == 2 and c2 > 0:
		c += c2
		c2 = 0
	elif i[0] == 3:
		st.append(i[1])
		while len(st) and st[-1] < speed:
			c += 1
			st.pop()
	elif i[0] == 4:
		c2 = 0
	elif i[0] == 5:
		st = []
	elif i[0] == 6:
		c2 += 1
print(c)


def Task485D():
	cur_speed = 0
	is_outstrip = 0
	err_count = 0
	event_speed_limit = []
	event_count = int(input())
	for a in range(event_count):
		ev = list(map(int, input().split()))
		if ev[0] == 1:
			cur_speed = ev[1]
			while len(event_speed_limit) > 0:
				if cur_speed > event_speed_limit[len(event_speed_limit) - 1]:
					event_speed_limit.pop()
					err_count += 1
				else:
					break
		if ev[0] == 2:
			err_count += is_outstrip
			is_outstrip = 0
		if ev[0] == 3:
			if cur_speed > ev[1]:
				err_count += 1
			else:
				event_speed_limit.append(ev[1])
		if ev[0] == 4:
			is_outstrip = 0
		if ev[0] == 5:
			event_speed_limit.clear()
		if ev[0] == 6:
			is_outstrip += 1
	print(err_count)
Task485D()


import collections
n = int(input())
(x, v) = map(int, input().split())
o = collections.deque()
q = 0
k = 0
for i in range(1, n):
	s = input()
	if s[0] == '1':
		(x, v) = map(int, s.split())
		while len(o) > 0 and o[-1] < v:
			o.pop()
			k += 1
	if s[0] == '2':
		k += q
		q = 0
	if s[0] == '3':
		(x, y) = map(int, s.split())
		if v <= y:
			o.append(y)
		else:
			k += 1
	if s[0] == '4':
		q = 0
	if s[0] == '5':
		o.clear()
	if s[0] == '6':
		q += 1
print(k)


n = int(input())
events = []
for i in range(n):
	events.append(list([int(s) for s in input().split()]))
max_speeds = []
overtaking_forbidden = 0
current_speed = 0
ignores = 0
for event in events:
	if event[0] == 1:
		current_speed = event[1]
		while max_speeds and current_speed > max_speeds[-1]:
			max_speeds.pop()
			ignores += 1
	elif event[0] == 2:
		ignores += overtaking_forbidden
		overtaking_forbidden = 0
	elif event[0] == 3:
		if current_speed > event[1]:
			ignores += 1
		else:
			max_speeds.append(event[1])
	elif event[0] == 4:
		overtaking_forbidden = 0
	elif event[0] == 5:
		max_speeds = []
	elif event[0] == 6:
		overtaking_forbidden += 1
print(ignores)


n = int(input())
speed = 0
overtake_allowed = True
just_overtake_violation = False
speed_signs = []
violations = 0
overtake_passed = 0
for i in range(n):
	arr = [int(a) for a in input().split(' ')]
	if arr[0] == 1:
		if arr[1] > speed:
			speed = arr[1]
			for j in range(len(speed_signs) - 1, -1, -1):
				if speed > speed_signs[j]:
					violations += 1
					del speed_signs[j]
				else:
					break
		else:
			speed = arr[1]
	if arr[0] == 2:
		violations += overtake_passed
		overtake_passed = 0
	if arr[0] == 3:
		if speed > arr[1]:
			violations += 1
		else:
			speed_signs.append(arr[1])
	if arr[0] == 4:
		overtake_passed = 0
	if arr[0] == 5:
		speed_signs = []
	if arr[0] == 6:
		overtake_passed += 1
print(violations)


speeds = [1000000]
overtakes = [True]
count = 0
speed = 0
n = int(input())
for e in range(n):
	inp = list(map(int, input().split()))
	if inp[0] == 4:
		overtakes.append(True)
	elif inp[0] == 6:
		overtakes.append(False)
	elif inp[0] == 5:
		speeds.append(1000000)
	elif inp[0] == 3:
		speeds.append(inp[1])
		while speed > speeds[-1]:
			count += 1
			speeds.pop()
	elif inp[0] == 2:
		while not overtakes[-1]:
			count += 1
			overtakes.pop()
	else:
		while inp[1] > speeds[-1]:
			count += 1
			speeds.pop()
		speed = inp[1]
print(count)


n = int(input())
ps = None
seen_sl = [float('inf')]
seen_ot = [True]
answer = 0
for i in range(n):
	line = list(map(int, input().split()))
	t = line[0]
	if t == 1:
		ps = line[1]
		while ps > seen_sl[-1]:
			answer += 1
			seen_sl.pop(-1)
	elif t == 2:
		while not seen_ot[-1]:
			answer += 1
			seen_ot.pop(-1)
	elif t == 3:
		seen_sl.append(line[1])
		while ps > seen_sl[-1]:
			answer += 1
			seen_sl.pop(-1)
	elif t == 4:
		seen_ot.append(True)
	elif t == 5:
		seen_sl.append(float('inf'))
	elif t == 6:
		seen_ot.append(False)
print(answer)


n = int(input())
over = []
speed = []
for x in range(n):
	ab = input()
	if len(ab) > 1:
		(a, b) = ab.split()
	else:
		a = ab
	if a == '1' or a == '3' or a == '5':
		if a == '5':
			speed.append([5, 2 ** 31 - 1])
		else:
			speed.append([int(a), int(b)])
	else:
		over.append(int(a))
overignore = 0
oversum = 0
i = len(over) - 1
while i >= 0:
	if over[i] == 2:
		oversum += 1
	elif over[i] == 4:
		oversum = 0
	if over[i] == 6 and oversum > 0:
		overignore += 1
	i -= 1
curspeed = []
stack = []
stack.append(2 ** 31 - 1)
i = 0
while i < len(speed):
	if speed[i][0] == 1:
		curspeed.append(speed[i][1])
	else:
		curspeed.append(curspeed[-1])
		stack.append(speed[i][1])
	i += 1
speedignore = 0
i = len(speed) - 1
while i >= 0:
	if speed[i][0] != 1 and speed[i][1] == stack[-1]:
		if curspeed[i] > stack[-1]:
			stack.pop()
			speedignore += 1
		else:
			stack.pop()
			i -= 1
	elif curspeed[i] > stack[-1]:
		stack.pop()
		speedignore += 1
	else:
		i -= 1
print(speedignore + overignore)