An ant moves on the real line with constant speed of $1$ unit per second. It starts at $0$ and always moves to the right (so its position increases by $1$ each second).

There are $n$ portals, the $i$-th of which is located at position $x_i$ and teleports to position $y_i < x_i$. Each portal can be either active or inactive. The initial state of the $i$-th portal is determined by $s_i$: if $s_i=0$ then the $i$-th portal is initially inactive, if $s_i=1$ then the $i$-th portal is initially active. When the ant travels through a portal (i.e., when its position coincides with the position of a portal):

if the portal is inactive, it becomes active (in this case the path of the ant is not affected);

if the portal is active, it becomes inactive and the ant is instantly teleported to the position $y_i$, where it keeps on moving as normal.

How long (from the instant it starts moving) does it take for the ant to reach the position $x_n + 1$? It can be shown that this happens in a finite amount of time. Since the answer may be very large, compute it modulo $998\,244\,353$.


-----Input-----

The first line contains the integer $n$ ($1\le n\le 2\cdot 10^5$) — the number of portals.

The $i$-th of the next $n$ lines contains three integers $x_i$, $y_i$ and $s_i$ ($1\le y_i < x_i\le 10^9$, $s_i\in\{0,1\}$) — the position of the $i$-th portal, the position where the ant is teleported when it travels through the $i$-th portal (if it is active), and the initial state of the $i$-th portal.

The positions of the portals are strictly increasing, that is $x_1<x_2<\cdots<x_n$. It is guaranteed that the $2n$ integers $x_1, \, x_2, \, \dots, \, x_n, \, y_1, \, y_2, \, \dots, \, y_n$ are all distinct.


-----Output-----

Output the amount of time elapsed, in seconds, from the instant the ant starts moving to the instant it reaches the position $x_n+1$. Since the answer may be very large, output it modulo $998\,244\,353$.


-----Examples-----

Input
4
3 2 0
6 5 1
7 4 0
8 1 1
Output
23
Input
1
454971987 406874902 1
Output
503069073
Input
5
243385510 42245605 0
644426565 574769163 0
708622105 208990040 0
786625660 616437691 0
899754846 382774619 0
Output
899754847
Input
5
200000000 100000000 1
600000000 400000000 0
800000000 300000000 0
900000000 700000000 1
1000000000 500000000 0
Output
3511295


-----Note-----

Explanation of the first sample: The ant moves as follows (a curvy arrow denotes a teleporting, a straight arrow denotes normal movement with speed $1$ and the time spent during the movement is written above the arrow). $$ 0 \stackrel{6}{\longrightarrow} 6 \leadsto 5 \stackrel{3}{\longrightarrow} 8 \leadsto 1 \stackrel{2}{\longrightarrow} 3 \leadsto 2 \stackrel{4}{\longrightarrow} 6 \leadsto 5 \stackrel{2}{\longrightarrow} 7 \leadsto 4 \stackrel{2}{\longrightarrow} 6 \leadsto 5 \stackrel{4}{\longrightarrow} 9 $$ Notice that the total time is $6+3+2+4+2+2+4=23$.

Explanation of the second sample: The ant moves as follows (a curvy arrow denotes a teleporting, a straight arrow denotes normal movement with speed $1$ and the time spent during the movement is written above the arrow). $$ 0 \stackrel{454971987}{\longrightarrow} 454971987 \leadsto 406874902 \stackrel{48097086}{\longrightarrow} 454971988 $$ Notice that the total time is $454971987+48097086=503069073$.

Explanation of the third sample: Since all portals are initially off, the ant will not be teleported and will go straight from $0$ to $x_n+1=899754846+1=899754847$.

Difficulty: HARD
Tags: Dynamic programming

Sorting

Data structures
Skill types: Dynamic programming

Sorting

Data structures

Starter code:

Solutions:
n = 0
m = 200005
r = [0] * m
l = [0] * m
s = [0] * m
dp = [0] * m
sum = [0] * m
mod = 998244353

def lower_bound(v):
	l = 1
	ri = n
	ans = 0
	while ri >= l:
		mid = l + ri >> 1
		if r[mid] >= v:
			ri = mid - 1
			ans = mid
		else:
			l = mid + 1
	return ans
n = int(input())
for i in range(1, n + 1):
	(r[i], l[i], s[i]) = map(int, input().split())
ans = 0
for i in range(1, n + 1):
	ans = (ans + r[i] - r[i - 1]) % mod
	p = lower_bound(l[i]) - 1
	dp[i] = (r[i] - l[i] + sum[i - 1] - sum[p] + mod * 2) % mod
	sum[i] = (sum[i - 1] + dp[i]) % mod
	if s[i]:
		ans = (ans + dp[i]) % mod
print((ans + 1) % mod)


import sys, os, io
from sys import stdin
import math
from collections import defaultdict
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
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')
alphabets = list('abcdefghijklmnopqrstuvwxyz')
from types import GeneratorType

def bootstrap(f, stack=[]):

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

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

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

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

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

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

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

def li():
	return list(map(int, input().split()))
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = ii()
l = []
x = []
y = []
s = []
for i in range(n):
	l.append(li())
	x.append(l[-1][0])
	y.append(l[-1][1])
	s.append(l[-1][2])
dp = [0] * n
mod = 998244353
prefix = [0]
for i in range(n):
	whichportal = bisect_left(x, y[i])
	dp[i] += prefix[-1] - prefix[whichportal] + x[i] - y[i]
	dp[i] %= mod
	prefix.append(dp[i] + prefix[-1])
	prefix[-1] %= mod
ans = 0
for i in range(n):
	if s[i] == 1:
		ans += dp[i]
ans %= mod
print((ans + x[-1] + 1) % mod)


from bisect import bisect

def solve():
	MOD = 998244353
	n = int(input())
	x = [0] * n
	y = [0] * n
	s = [0] * n
	z = [0] * n
	p = [0] * (n + 1)
	r = 0
	for i in range(n):
		(x[i], y[i], s[i]) = map(int, input().split())
	for i in range(n):
		nn = bisect(x, y[i])
		z[i] = (p[i] - p[nn] + x[i] - y[i]) % MOD
		p[i + 1] = (p[i] + z[i]) % MOD
		if s[i] == 1:
			r = (r + z[i]) % MOD
	print((x[n - 1] + 1 + r) % MOD)
solve()


from bisect import bisect_left
from sys import stdin, gettrace
if gettrace():

	def inputi():
		return input()
else:

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

	def inputi():
		return stdin.buffer.readline()
MOD = 998244353

def solve():
	n = int(input())
	xys = [[int(a) for a in input().split()] for _ in range(n)]
	vs = [0]
	(xx, _, _) = list(zip(*xys))
	res = (xx[-1] + 1) % MOD
	for (x, y, s) in xys:
		si = bisect_left(xx, y)
		v = (x - y + vs[-1] - vs[si]) % MOD
		vs.append((vs[-1] + v) % MOD)
		if s == 1:
			res = (v + res) % MOD
	print(res)

def main():
	solve()
main()


mod = 998244353
n = int(input())
(y, s, x) = ([], [], [])
for i in range(n):
	(a, b, c) = [int(X) for X in input().split()]
	x.append(a)
	y.append(b)
	s.append(c)

def bs_first_greater(arr, start, end, val):
	if start > end:
		return -1
	mid = (start + end) // 2
	if arr[mid] > val:
		if mid == start:
			return mid
		elif arr[mid - 1] <= val:
			return mid
		else:
			return bs_first_greater(arr, start, mid - 1, val)
	else:
		return bs_first_greater(arr, mid + 1, end, val)
dp = [0 for x in range(n)]
dp[0] = x[0] - y[0]
prefixdp = [0 for x in range(n)]
prefixdp[0] += dp[0]

def givesum(i, j):
	if i == 0:
		return prefixdp[j]
	else:
		return prefixdp[j] - prefixdp[i - 1]
for i in range(1, n):
	next_portal = bs_first_greater(x, 0, n - 1, y[i])
	dp[i] += x[i] - y[i]
	if next_portal == i:
		pass
	else:
		dp[i] += givesum(next_portal, i - 1)
	dp[i] %= mod
	prefixdp[i] = (dp[i] + prefixdp[i - 1]) % mod
ans = (x[-1] + 1) % mod
for i in range(n):
	if s[i] == 1:
		ans += dp[i]
		ans %= mod
print(ans % mod)


M = 998244353
n = int(input())
a = list()
for _ in range(n):
	(x, y, s) = map(int, input().split())
	a.append([x, y, s])
pref = [0] * n
d = [0] * n
d[0] = pref[0] = a[0][0] - a[0][1]
for i in range(1, n):
	yi = a[i][1]
	l = -1
	r = n
	while r - 1 > l:
		g = (l + r) // 2
		if a[g][0] > yi:
			r = g
		else:
			l = g
	d[i] = (a[i][0] - a[i][1] + pref[i - 1] - pref[l]) % M
	pref[i] = pref[i - 1] + d[i]
ans = (a[-1][0] + 1 + sum([d[i] for i in range(n) if a[i][2]])) % M
print(ans)


from bisect import bisect

def readline():
	return map(int, input().split())
MOD = 998244353

def main():
	n = int(input())
	portals = [tuple(readline()) for __ in range(n)]
	ans = 0
	waste = []
	partial_sum = [0]
	for (j, (x, y, s)) in enumerate(portals):
		i = bisect(portals, (y, 0, 0))
		w = partial_sum[j] - partial_sum[i] + (x - y)
		w %= MOD
		waste.append(w)
		partial_sum.append(partial_sum[-1] + w)
		if s:
			ans += w
			ans %= MOD
	print((ans + x + 1) % MOD)
main()


import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2 * 10 ** 5 + 10)
write = lambda x: sys.stdout.write(x + '\n')
debug = lambda x: sys.stderr.write(x + '\n')
writef = lambda x: print('{:.12f}'.format(x))
n = int(input())
xs = []
ys = []
ss = []
for i in range(n):
	(x, y, s) = list(map(int, input().split()))
	xs.append(x)
	ys.append(y)
	ss.append(s)
dp = [0] * n
cum = [0] * (n + 1)
M = 998244353
from bisect import bisect_left as bl
for i in range(n):
	x = xs[i]
	y = ys[i]
	ind = bl(xs, y)
	v = cum[i] - cum[ind]
	dp[i] = v + (x - y)
	cum[i + 1] += cum[i] + dp[i]
	cum[i + 1] %= M
ans = []
val = 0
for i in range(n):
	x = xs[i]
	y = ys[i]
	s = ss[i]
	if s:
		val += dp[i]
		val %= M
ans = xs[-1] + val + 1
print(ans % M)


def find(i):
	left = 0
	right = n - 1
	if portal[0][0] >= i:
		return 0
	while left + 1 < right:
		m = (left + right) // 2
		if portal[m][0] < i:
			left = m
		else:
			right = m
	return right
N = 998244353
n = int(input())
portal = []
for _ in range(n):
	portal.append(list(map(int, input().split())))
M = portal[-1][0] + 1
for i in range(n):
	portal[i].append(find(portal[i][1]))
time = [0] * n
sum_time = [0] * (n + 1)
for j in range(n):
	time[j] = portal[j][0] - portal[j][1]
	time[j] += sum_time[j] - sum_time[portal[j][3]]
	time[j] %= N
	sum_time[j + 1] = time[j] + sum_time[j]
	sum_time[j + 1] %= N
t = portal[-1][0] + 1
for i in range(n):
	if portal[i][2]:
		t += time[i]
print(t % N)


import sys
input = sys.stdin.readline

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

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

def LI():
	return [*map(int, input().strip().split())]
import copy, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, combinations, groupby
from operator import itemgetter
from itertools import chain, combinations
MOD = 998244353
n = II()
(x, y, s) = ([], [], [])
for _ in range(n):
	inp = LI()
	x.append(inp[0])
	y.append(inp[1])
	s.append(inp[2])
preSum = [0]
comeBack = []
for i in range(n):
	ind = bisect_left(x, y[i])
	dis = (x[i] - y[i] + preSum[i] - preSum[ind]) % MOD
	comeBack.append(dis)
	preSum.append((preSum[-1] + dis) % MOD)
ans = (x[-1] + 1) % MOD
for i in range(n):
	if s[i]:
		ans = (ans + comeBack[i]) % MOD
print(ans)


import bisect
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
M = 998244353

def main(t):
	n = int(input())
	dp = [0] * (n + 1)
	accudp = [0] * (n + 1)
	state = [0] * n
	trans = []
	for i in range(n):
		(y, x, f) = map(int, input().split())
		state[i] = f
		trans.append(y)
		loc = bisect.bisect(trans, x)
		dp[i + 1] = accudp[i] - accudp[loc] + y - x
		dp[i + 1] = dp[i + 1] % M
		accudp[i + 1] = accudp[i] + dp[i + 1]
		accudp[i + 1] = accudp[i + 1] % M
	ans = (trans[-1] + 1) % M
	for i in range(n):
		if state[i] == 1:
			ans += dp[i + 1]
			ans = ans % M
	print(ans)
T = 1
t = 1
while t <= T:
	main(t)
	t += 1


n = int(input())
x = [0] * n
y = [0] * n
s = [0] * n
dp = [0] * n
mod = 998244353
sumdp = [0] * (n + 1)
result = 0
for i in range(n):
	(x[i], y[i], s[i]) = map(int, input().split(' '))
from bisect import bisect
for i in range(n):
	pos = bisect(x, y[i])
	dp[i] = (x[i] - y[i] + sumdp[i] - sumdp[pos]) % mod
	sumdp[i + 1] = (sumdp[i] + dp[i]) % mod
	if s[i] == 1:
		result += dp[i] % mod
print((x[-1] + 1 + result) % mod)


from bisect import bisect
MD = 998244353
n = int(input())
cur = [0]
(dp1, dp2) = ([0] + n * [0] for _ in range(2))
bef = 0
for i in range(n):
	(x, y, s) = map(int, input().split())
	goes = bisect(cur, y) - 1
	dp1[i + 1] = dp1[i] + (x - bef) if s == 0 else dp1[i] + (x - bef) - (y - cur[goes]) + (dp2[i] - dp2[goes]) + (x - bef)
	dp2[i + 1] = dp2[i] + (x - bef) - (y - cur[goes]) + (dp2[i] - dp2[goes]) + (x - bef)
	dp1[i + 1] %= MD
	dp2[i + 1] %= MD
	bef = x
	cur.append(bef)
print((1 + dp1[-1]) % MD)


from bisect import bisect_left
MOD = 998244353

def dynamic_ant(n, x, y, s):
	time_all_active = [0 for _ in range(n + 1)]
	for i in range(1, n + 1):
		j = bisect_left(x, y[i])
		time_all_active[i] = 2 * (time_all_active[i - 1] + x[i] - x[i - 1]) - (time_all_active[j - 1] + y[i] - x[j - 1])
		time_all_active[i] %= MOD
	actual = [0 for _ in range(n + 1)]
	for i in range(1, n + 1):
		actual[i] = actual[i - 1] + x[i] - x[i - 1]
		if s[i] == 1:
			j = bisect_left(x, y[i])
			actual[i] += time_all_active[i - 1] - time_all_active[j - 1] - (y[i] - x[j - 1]) + (x[i] - x[i - 1])
			actual[i] %= MOD
	return (actual[-1] + 1) % MOD
n = int(input())
s = [0 for _ in range(n + 1)]
x = [0 for _ in range(n + 1)]
y = [0 for _ in range(n + 1)]
for i in range(1, n + 1):
	(x[i], y[i], s[i]) = (int(t) for t in input().split(' '))
print(dynamic_ant(n, x, y, s))


import sys
from sys import stdin
import bisect
tt = 1
mod = 998244353
for loop in range(tt):
	n = int(stdin.readline())
	xlis = [0]
	ylis = [0]
	slis = [0]
	for i in range(n):
		(x, y, s) = map(int, stdin.readline().split())
		xlis.append(x)
		ylis.append(y)
		slis.append(s)
	dp = [0]
	dpsum = [0]
	for i in range(1, n + 1):
		(x, y) = (xlis[i], ylis[i])
		subx = bisect.bisect_right(xlis, y) - 1
		ndp = x - y + dpsum[-1] - dpsum[subx]
		dp.append(ndp % mod)
		dpsum.append((dpsum[-1] + ndp) % mod)
	ans = xlis[-1] + 1
	for i in range(1, n + 1):
		if slis[i] == 1:
			ans += dp[i]
	print(ans % mod)


import sys
input = sys.stdin.readline
n = int(input())
T = [list(map(int, input().split())) for i in range(n)]
mod = 998244353
ANS = T[-1][0] + 1
D = []
for (x, y, c) in T:
	D.append(x)
	D.append(y)
D = sorted(set(D))
DICT = {D[i]: i + 1 for i in range(len(D))}
LEN = len(D) + 5
BIT = [0] * (LEN + 1)

def update(v, w):
	while v <= LEN:
		BIT[v] += w
		BIT[v] %= mod
		v += v & -v

def getvalue(v):
	ANS = 0
	while v != 0:
		ANS += BIT[v]
		ANS %= mod
		v -= v & -v
	return ANS
for (x, y, c) in T[::-1]:
	g = getvalue(DICT[x])
	if c == 1:
		ANS += (g + 1) * (x - y)
		update(DICT[y], g + 1)
	else:
		ANS += g * (x - y)
		update(DICT[y], g)
	ANS %= mod
print(ANS)


import sys
input = sys.stdin.readline

def make_tree(n):
	i = 2
	while True:
		if i >= n * 2:
			tree = [0] * i
			break
		else:
			i *= 2
	return tree

def update(i, x):
	i += len(tree) // 2
	tree[i] = x
	i //= 2
	while True:
		if i == 0:
			break
		tree[i] = tree[2 * i] + tree[2 * i + 1]
		i //= 2
	return

def get_sum(s, t):
	s += len(tree) // 2
	t += len(tree) // 2
	ans = 0
	while True:
		if s > t:
			break
		if s % 2 == 0:
			s //= 2
		else:
			ans += tree[s]
			s = (s + 1) // 2
		if t % 2 == 1:
			t //= 2
		else:
			ans += tree[t]
			t = (t - 1) // 2
	return ans
n = int(input())
mod = 998244353
s = [0] * n
xy = []
z = []
d = dict()
for i in range(n):
	(x, y, s0) = map(int, input().split())
	s[i] = s0
	xy.append((x, y))
	z.append(x)
	z.append(y)
z.sort()
for i in range(2 * n):
	d[z[i]] = i + 1
tree = make_tree(2 * n + 5)
ans = (x + 1) % mod
for i in range(n):
	(x, y) = xy[i]
	(dx, dy) = (d[x], d[y])
	d0 = x - y
	c = get_sum(dy, dx)
	cd = (c + d0) % mod
	if s[i]:
		ans += cd
		ans %= mod
	update(dx, cd)
print(ans)


MOD = 998244353

def solve():
	n = int(input())
	ini = []
	out = []
	state = []
	for i in range(n):
		(a, b, c) = list(map(int, input().split()))
		ini.append(a)
		out.append(b)
		state.append(c)
	pos = []
	for a in out:
		le = 0
		ri = n - 1
		while le < ri:
			mid = (le + ri) // 2
			if a > ini[mid]:
				le = mid + 1
			else:
				ri = mid
		pos.append(le)
	dp = [ini[0] - out[0]]
	for i in range(1, n):
		le = pos[i]
		a = (dp[i - 1] + (ini[i] - ini[i - 1]) * 2 + ini[le] - out[i]) % MOD
		if le:
			dp.append((a + dp[i - 1] - dp[le - 1] - ini[le] + ini[le - 1]) % MOD)
		else:
			dp.append((a + dp[i - 1]) % MOD)
	ans = ini[0] + 1
	if state[0]:
		ans = (ans + dp[0]) % MOD
	for i in range(1, n):
		if state[i]:
			ans = (ans + dp[i] - dp[i - 1]) % MOD
		else:
			ans = (ans + ini[i] - ini[i - 1]) % MOD
	return ans % MOD
import sys
input = lambda : sys.stdin.readline().rstrip()
print(solve())


from sys import stdin, stdout
n = int(stdin.readline())
xys_a = []
for _ in range(n):
	xys_a.append(list(map(int, stdin.readline().split())))
xys_a.sort(key=lambda a: a[0])
q_a = [xys_a[0][0] - xys_a[0][1]]
qs_a = [xys_a[0][0] - xys_a[0][1]]
MOD = 998244353
for i in range(1, n):
	l = 0
	h = i
	while l < h:
		m = (l + h) // 2
		if xys_a[i][1] <= xys_a[m][0]:
			h = m
		else:
			l = m + 1
	qr = xys_a[i][0] - xys_a[i][1]
	if l < i:
		qr += qs_a[i - 1]
		qr %= MOD
		if l - 1 >= 0:
			qr -= qs_a[l - 1]
			qr = (qr + MOD) % MOD
	q_a.append(qr)
	qs_a.append((qs_a[-1] + q_a[-1]) % MOD)
ans = 0
for i in range(n):
	if xys_a[i][2] == 1:
		ans += q_a[i]
		ans %= MOD
ans += xys_a[-1][0] + 1
ans %= MOD
stdout.write(str(ans))


n = int(input())
(X, Y, S) = ([], [], [])
P = 998244353
T = [0] * (n + 1)

def findIndex(L, p):
	n = len(L)
	(l, r) = (0, n)
	guess = n // 2
	while r > l:
		guess = (r + l) // 2
		if L[guess] <= p:
			l = guess + 1
		elif L[guess] > p:
			r = guess
	return l
for i in range(n):
	(xi, yi, si) = map(int, input().split())
	X.append(xi)
	Y.append(yi)
	S.append(si)
	j = findIndex(X, yi)
	T[i + 1] = (xi - yi + 2 * T[i] - T[j]) % P
xn = X[-1]
total = xn + 1
Test = [0] * n
for i in range(n):
	si = S[i]
	total += (T[i + 1] - T[i]) * si
	total %= P
print(total)


def naiveSolve():
	return

def main():
	n = int(input())
	x = []
	y = []
	s = []
	for _ in range(n):
		(xx, yy, ss) = readIntArr()
		x.append(xx)
		y.append(yy)
		s.append(ss)
	t = [0] * n
	p = [0] * n

	def update(i, time):
		time %= MOD
		t[i] = time
		p[i] = time
		if i - 1 >= 0:
			p[i] += p[i - 1]
			p[i] %= MOD

	def rangeQuery(tLeft, tRight):
		iLeft = -1
		b = n
		while b > 0:
			while b + iLeft < n and x[b + iLeft] <= tLeft:
				iLeft += b
			b //= 2
		iLeft += 1
		iRight = -1
		b = n
		while b > 0:
			while b + iRight < n and x[b + iRight] < tRight:
				iRight += b
			b //= 2
		if iRight == -1:
			return 0
		if iLeft == 0:
			return p[iRight]
		else:
			return p[iRight] - p[iLeft - 1]
	for i in range(n):
		time = x[i] - y[i] + rangeQuery(y[i], x[i])
		update(i, time)
	pos = 0
	ans = 1
	for i in range(n):
		ans += x[i] - pos
		ans %= MOD
		pos = x[i]
		if s[i] == 1:
			ans += t[i]
			ans %= MOD
	print(ans)
	return
import sys
input = sys.stdin.buffer.readline

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(l, r):
	print('? {} {}'.format(l, r))
	sys.stdout.flush()
	return int(input())

def answerInteractive(x):
	print('! {}'.format(x))
	sys.stdout.flush()
inf = float('inf')
MOD = 998244353
from math import gcd, floor, ceil
for _abc in range(1):
	main()


from bisect import bisect_right, bisect_left
n = int(input())
arr = []
brr = []
mod = 998244353
for i in range(n):
	(x, y, f) = map(int, input().split())
	arr.append([y, f])
	brr.append(x)
sum_arr = [0 for i in range(n + 6)]
count = 0
for i in range(n):
	bis = bisect_right(brr, arr[i][0])
	sum_arr[i] = (sum_arr[i - 1] - sum_arr[bis - 1] + brr[i] - arr[i][0]) % mod
	if arr[i][1] == 1:
		count = (count + sum_arr[i]) % mod
	sum_arr[i] = (sum_arr[i] + sum_arr[i - 1]) % mod
print((count + brr[-1] + 1) % mod)


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')
mod = 998244353
n = int(input())
(y, s, x) = ([], [], [])
for i in range(n):
	(a, b, c) = [int(X) for X in input().split()]
	x.append(a)
	y.append(b)
	s.append(c)

def bs_first_greater(arr, start, end, val):
	while start <= end:
		mid = (start + end) // 2
		if arr[mid] > val:
			if mid == start:
				return mid
			elif arr[mid - 1] <= val:
				return mid
			else:
				end = mid - 1
		else:
			start = mid + 1
	return -1
dp = [0 for x in range(n)]
dp[0] = x[0] - y[0]
prefixdp = [0 for x in range(n)]
prefixdp[0] += dp[0]

def givesum(i, j):
	if i == 0:
		return prefixdp[j]
	else:
		return prefixdp[j] - prefixdp[i - 1]
for i in range(1, n):
	next_portal = bs_first_greater(x, 0, n - 1, y[i])
	dp[i] += x[i] - y[i]
	if next_portal == i:
		pass
	else:
		dp[i] += givesum(next_portal, i - 1)
	dp[i] %= mod
	prefixdp[i] = (dp[i] + prefixdp[i - 1]) % mod
ans = (x[-1] + 1) % mod
for i in range(n):
	if s[i] == 1:
		ans += dp[i]
		ans %= mod
print(ans % mod)


import sys, os, io
from sys import stdin
from bisect import bisect_left
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')

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

def li():
	return list(map(int, input().split()))
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = ii()
l = []
x = []
y = []
s = []
for i in range(n):
	l.append(li())
	x.append(l[-1][0])
	y.append(l[-1][1])
	s.append(l[-1][2])
dp = [0] * n
mod = 998244353
prefix = [0]
for i in range(n):
	whichportal = bisect_left(x, y[i])
	dp[i] += prefix[-1] - prefix[whichportal] + x[i] - y[i]
	dp[i] %= mod
	prefix.append(dp[i] + prefix[-1])
	prefix[-1] %= mod
ans = 0
for i in range(n):
	if s[i] == 1:
		ans += dp[i]
ans %= mod
print((ans + x[-1] + 1) % mod)