Problem:


Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j) 

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.



Sample input:
5 2
1 1
3 4


Sample output:
4

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
mod = 998244353

LR = [tuple(map(int, input().split())) for _ in range(K)]
LR.sort()

dp = [0] * (N + 1)
dp[1] = 1
for i in range(1, N):
    if dp[i] <= 0:
        continue
    for L, R in LR:
        for d in range(L, R + 1):
            if i + d < N + 1:
                dp[i + d] += dp[i]
                dp[i + d] %= mod

print(dp[N])

Submission status: Time Limit Exceeded

Solution code:
n, k = list(map(int, input().split()))
lrs = [0] * k
for i in range(k):
     lr = list(map(int, input().split()))
     lrs[i] = range(lr[0], lr[1]+1)

s = list()
for lr in lrs:
    for d in lr:
        s.append(d)

mod = 998244353
i = 1
dp = [0] * (n+1)
dp[i] = 1
for i in range(n+1):
    if dp[i] == 0:
        continue
    for d in s:
        if i+d <= n:
            dp[i+d] = (dp[i+d] + dp[i]) % mod

print(dp[n] % mod)

Submission status: Time Limit Exceeded

Solution code:

def input_int():
    return(int(input()))

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

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

import sys
sys.setrecursionlimit(100000000)

def run():
    n, k = input_int_map()

    k_set = set()
    for _ in range(k):
        l, r = input_int_map()

        for i in range(l, r + 1):
            k_set.add(i)

    result = find_pettern(n - 1, k_set, {})
    result = result % 998244353
    print(result)

def find_pettern(n: int, k_set: {int}, memo: {}) -> int:

    if n < 0:
        return 0

    if n == 0:
        return 1

    if n in memo:
        return memo[n]

    count_num = 0
    for k in k_set:
        count_num += find_pettern(n - k, k_set, memo)

    memo[n] = count_num

    return count_num

run()

Submission status: Time Limit Exceeded

Solution code:

import numpy as np

N,K = list(map(int, input().split()))
LRs = [list(map(int, input().split())) for _ in range(K)]



move_list = []
checker = np.zeros(N+1 ,dtype = int)
for LR in LRs:
#    for i in range(LR[0], LR[1]+1):
#        move_list.append(i)
    for i in range(LR[0], LR[1]+1):
        checker[i] = 1

#print(move_list)
#move_list.sort()

#print(move_list)
for index, check in enumerate(checker):
    if(check == 1):
        move_list.append(index)

#print(move_list)

dp = np.zeros(N+1, dtype = int)
dp[1] = 1

for i in range(1, N+1):
    for j in move_list:
        if(i < j):
            break
#        print(i,j)
        dp[i] = (dp[i] +dp[i-j]) % 998244353

print(dp[N])

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
d = [0]*(N+1)
l = []
for i in range(K):
    l.append(list(map(int, input().split())))
di = []
for i in range(K):
    a, b = l[i][0], l[i][1]
    for j in range(b-a+1):
        di.append(a+j)


adj = {}
for i in range(N-1):
    lis = [i+1+j for j in di if i+1+j<=N]
    adj[i+1] = lis

ans = [0]*(N+1)
ans[1] = 1
for i in range(N-1):
    #i+1番目
    for x in adj[i+1]:
        ans[x] = ans[x] + ans[i+1]
        if(ans[x]>998244353):
            ans[x] = ans[x]%998244353
print (ans[-1]%998244353)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int, input().split())
s = set()
for i in range(k):
  l,r = map(int, input().split())
  for _ in range(l,r+1):
    s.add(_)
a = [0]*(2*10**5+1)
a[1] = 1
for i in range(2*10**5):
  for d in s:
    if i+d <= 2*10**5:
      a[i+d] += a[i]%998244353
    else:
      break
print(a[n]%998244353)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

def get_input() -> tuple:
    """
    標準入力を取得する.

    Returns:\n
        tuple: 標準入力
    """
    # 標準入力を取得
    N, K = list(map(int, input().split()))
    L, R = [], []
    for k in range(K):
        L_k, R_k = list(map(int, input().split()))
        L.append(L_k)
        R.append(R_k)

    return N, K, L, R


def main(N: int, K: int, L: list, R: list) -> None:
    """
    メイン処理.

    Args:\n
        N (int): マスの数(2 <= N <= 2 * 10**5)
        K (int): 区関数(1 <= K <= min(K, N))
        L (list): 区間の下限(1 <= L_i <= R_i <= N)
        R (list): 区間の上限(1 <= L_i <= R_i <= N)
    """
    # 求解処理
    S = set()
    for k in range(K):
        for s in range(L[k], R[k] + 1):
            S.add(s)
    S = sorted(S)

    m = {i: 0 if i != 1 else 1 for i in range(1, N + 1)}
    for i in range(1, N):
        m_i = m[i]
        if m_i == 0:
            continue
        for s in S:
            if i + s <= N:
                m[i + s] += m_i
            else:
                break

    ans = m[N] % 998244353

    # 結果出力
    print(ans)


if __name__ == "__main__":
    # 標準入力を取得
    N, K, L, R = get_input()

    # メイン処理
    main(N, K, L, R)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

mod = 998244353

N, K = map(int, input().split())
LR = []
lmin = float('inf')

for _ in range(K):
    l, r = map(int, input().split())
    LR.append((l, r))
    lmin = min(lmin, l)

dp = np.array([0] * (N+1))
dp[1] += 1

for i in range(1, N-lmin+1):
    now = dp[i] % mod
    if now:
        for l, r in LR:
            if l <= N:
            # try:
                dp[i+l:min(N+1, i+r+1)] += now
            # except:
            else:
                break

print(dp[-1] % mod)

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline

n, k = map(int, input().split())
a = [0] * (n+1)
index = 0
for _ in range(k):
    l, r = map(int, input().split())
    for u in range(l, r+1):
        a[index] = u
        index += 1

mod = 998244353


@lru_cache(maxsize=10**8)
def calc(x):
    if x <= 0:
        return 1
    ret = 0
    for i in range(index):
        u = a[i]
        if x - u >= 0:
            ret += calc(x - u)
            ret %= mod
    return ret


print(calc(n-1))

Submission status: Time Limit Exceeded

Solution code:
MOD = 998244353
N, K = map(int, input().split())
S = set()
for _ in range(K):
    L, R = map(int, input().split())
    for j in range(L, R + 1):
        if j not in S:
            S.add(j)
C = [0] * N
C[0] = 1
for i in range(N):
    for s in S:
        if i + s < N:
            C[i + s] += C[i]
print(C[N - 1] % MOD)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
def main():
    import numpy as np

    N, K = map(int, input().split())
    S = set()
    section = []
    for _ in range(K):
        l, r = map(int, input().split())
        section.append((l, r + 1))
        for n in range(l, r + 1):
            S.add(n)
    MOD = 998244353

    dp = np.zeros(N, dtype=np.int64)
    dp[0] = 1
    for i in range(N):
        res = dp[i] % MOD
        for left, right in section:
            right = min(i + right, N)
            left = i + left
            dp[left:right] += res
    print(dp[-1] % MOD)
    # print(dp)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
inp= list(map(int,input().split()))
n=inp[0]
k=inp[1]

def countWays(arr, m, N): 
  
    count = [0 for i in range(N + 1)] 
      
    # base case 
    count[0] = 1
      
    # Count ways for all values up  
    # to 'N' and store the result 
    for i in range(1, N + 1): 
        for j in range(m): 
  
            # if i >= arr[j] then 
            # accumulate count for value 'i' as 
            # ways to form value 'i-arr[j]' 
            if (i >= arr[j]): 
                count[i] += count[i - arr[j]] 
      
    # required number of ways  
    return count[N] 

l=[]
for i in range(k):
	inp= list(map(int,input().split()))
	a=inp[0]
	b=inp[1]
	l.extend(list(range(a,b+1)))


res =countWays(l,len(l),n-1)

res %= 998244353

print(res)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
lists = []
mod = 998244353

for i in range(k):
    tmp = tuple(map(int, input().split()))
    lists += [i for i in range(tmp[0], tmp[1] + 1)]

lists.sort()

dp = [0 for i in range(n)]
dp[0] = 1

for i in range(1, n):
    for num in lists:
        if i < num:
            break

        dp[i] += dp[i - num]
    dp[i] %= mod

print(dp[n - 1])

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int, input().split())
mod=998244353
D=[0]*(2*N+2)
D[0]=1
A=[]
for i in range(K):
  L,R=map(int, input().split())
  A.append((L,R))
A=sorted(A)
#print(A)
for i in range(N-1):
  for a,b in A:
    if i+a<=N:
      for j in range(i+a,min(i+b+1,N)):
        D[j]+=D[i]
        D[j]%=mod
print(D[N-1])

Submission status: Time Limit Exceeded

Solution code:
mod=998244353
n,k=map(int,input().split())
s=set()
for i in range (k):
    x,y=map(int,input().split())
    for m in range (x,y+1):
        s.update([m])

dp=[0 for i in range (n+1)]
dp[1]=1


for i in range (2,n+1):
    x=0
    for val in s:
        if (i-val)<0:
            continue
        x=(x%mod+(dp[i-val]%mod))%mod
    dp[i]=x

print (dp[n])

Submission status: Time Limit Exceeded

Solution code:
mod = 998244353
N, K = map(int,input().split())
S = []
for i in range(K):
    l,r = map(int,input().split())
    for j in range(r-l+1):
        S.append(l+j)
A = [0]*N
A[0] = 1
for i in range(N):
    for j in range(len(S)):
        if i - S[j]  >= 0:
            A[i] = (A[i] + A[i-S[j]]) % mod
print(A[-1])

Submission status: Time Limit Exceeded

Solution code:
N, K = [int(_) for _ in input().split()]
LR = [[int(_) for _ in input().split()] for _ in range(K)]
mod = 998244353


class LazySegmentTree():
    def __init__(self, array, f, g, h, ti, ei):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
            T x T -> T
            T is dat
        g : func
            binary operation of the monoid
            T x E -> T
            T is dat, E is laz
        h : func
            binary operation of the monoid
            E x E -> T
            E is laz
        ti : T
            identity element of T
        ei : E
            identity element of E
        """
        self.f = f
        self.g = g
        self.h = h
        self.ti = ti
        self.ei = ei
        self.height = height = len(array).bit_length()
        self.n = n = 2**height
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        self.laz = [ei] * (2 * n)
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def reflect(self, k):
        dat = self.dat
        ei = self.ei
        laz = self.laz
        g = self.g
        return self.dat[k] if laz[k] is ei else g(dat[k], laz[k])

    def evaluate(self, k):
        laz = self.laz
        ei = self.ei
        reflect = self.reflect
        dat = self.dat
        h = self.h
        if laz[k] is ei:
            return
        laz[(k << 1) | 0] = h(laz[(k << 1) | 0], laz[k])
        laz[(k << 1) | 1] = h(laz[(k << 1) | 1], laz[k])
        dat[k] = reflect(k)
        laz[k] = ei

    def thrust(self, k):
        height = self.height
        evaluate = self.evaluate
        for i in range(height, 0, -1):
            evaluate(k >> i)

    def recalc(self, k):
        dat = self.dat
        reflect = self.reflect
        f = self.f
        while k:
            k >>= 1
            dat[k] = f(reflect((k << 1) | 0), reflect((k << 1) | 1))

    def update(self, a, b, x):  # set value at position [a, b) (0-indexed)
        thrust = self.thrust
        n = self.n
        h = self.h
        laz = self.laz
        recalc = self.recalc
        a += n
        b += n - 1
        l = a
        r = b + 1
        thrust(a)
        thrust(b)
        while l < r:
            if l & 1:
                laz[l] = h(laz[l], x)
                l += 1
            if r & 1:
                r -= 1
                laz[r] = h(laz[r], x)
            l >>= 1
            r >>= 1
        recalc(a)
        recalc(b)

    def set_val(self, a, x):
        n = self.n
        thrust = self.thrust
        dat = self.dat
        laz = self.laz
        recalc = self.recalc
        ei = self.ei
        a += n
        thrust(a)
        dat[a] = x
        laz[a] = ei
        recalc(a)

    def query(self, a, b):  # result on interval [a, b) (0-indexed)
        f = self.f
        ti = self.ti
        n = self.n
        thrust = self.thrust
        reflect = self.reflect
        a += n
        b += n - 1
        thrust(a)
        thrust(b)
        l = a
        r = b + 1
        vl = vr = ti
        while l < r:
            if l & 1:
                vl = f(vl, reflect(l))
                l += 1
            if r & 1:
                r -= 1
                vr = f(reflect(r), vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


#RSQ and RAQ
array = [0] + [1] + [0] * 2 * N
f = lambda a, b: a if a else b
g = lambda a, b: (a + b) % mod
h = lambda a, b: (a + b) % mod
ti = 0
ei = 0

LST = LazySegmentTree(array=array, ti=ti, ei=ei, f=f, g=g, h=h)
for x in range(1, N):
    v = LST.query(x, x + 1)
    for l, r in LR:
        LST.update(x + l, x + r + 1, v)
ans = LST.query(N, N + 1)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500)

N, K = map(int, input().split())
LR = [tuple(map(int, input().split())) for _ in range(K)]

jList = {j for l, r in LR for j in range(l, r+1)}
minL = min(jList)

mod = 998244353

result = [None for _ in range(N)]
result[0] = 1
#for ni in range(1, N):
def dp(ni):
  if result[ni] is not None: return result[ni]
  result[ni] = 0
  for j in jList:
    if ni-j<0: continue
    result_ni_j = dp(ni-j)
    result[ni] = (result[ni]+result_ni_j) % mod
  return result[ni]


print(dp(N-1))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,K = map(int,input().split())
figs = set()
for _ in [0] * K:
  a,b = map(int,input().split())
  for i in range(a,b+1):
    figs.add(i)
DP = [0]*N
DP[0] = 1
for i in range(N):
  for item in figs:
    if i - item >= 0:
      DP[i] = DP[i - item]+DP[i]
print(DP[-1]%998244353)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())

arr={0}
for i in range(K):
    a,b=map(int,input().split())
    arr|=set([j for j in range(a,b+1)])

arr.discard(0)


dp=[[0]*N for i in range(N)] 
dp[0][0]=1

ans=0
for i in range(N):
    for j in range(i,N):
        if dp[i][j]!=0:
            for k in arr:
                if j+k<=N-1:
                    dp[i+1][j+k]+=dp[i][j]
    ans+=dp[i][-1]
            
print(ans%998244353)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
L = []
R = []
for _ in range(K):
  l, r = map(int, input().split())
  L.append(l)
  R.append(r)
L.sort()
R.sort()
DP = [0] * N
DP[0] = 1

for i in range(N):
  for j in range(len(L)):
    for k in range(L[j], R[j] + 1):
      if i - k < 0:
        break
      if 0 <= i - k < N:
        DP[i] += DP[i - k]
print(DP[-1]%998244353)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# -*- coding: UTF-8 -*-


def main():
    n, m = map(int, input().split())
    p = [list(map(int, input().split())) for _ in range(m)]
    s = set()
    for pp in p:
        s |= set(range(pp[0], pp[1]+1))
    s = list(s)
    s.sort()
    s = set(s)
    d = dict()
    d[1] = 1

    n_list = [n]
    for nn in n_list:
        for ss in s:
            if nn-ss > 0:
                if nn-ss not in n_list:
                    n_list.append(nn-ss)

    n_list = sorted(n_list)
    for i in n_list:
        if i == 1:
            continue
        ans = 0
        for ss in s:
            if i-ss > 0:
                ans += d[i - ss]
        d[i] = ans

    print(d[n] % 998244353)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(200000)

N,K=map(int,input().strip().split())
inf=998244353
S=[]
for _ in range(K):
    L,R=map(int,input().strip().split())
    for i in range(L,R+1):
        S.append(i)

dp=[-1 for _ in range(N)]
dp[0]=1
def rec(n,S,dp):
    if dp[n-1]!=-1:
        return dp[n-1]
    else:
        dp[n-1]=0
        for j in range(len(S)):
            x=n-S[j]
            if x>0:
                if dp[x-1]!=-1:
                    dp[n-1]+=dp[x-1]%inf
                else:
                    dp[x-1]=rec(x,S,dp)
                    dp[n-1]+=dp[x-1]%inf
        dp[n-1]=dp[n-1]%inf
        return dp[n-1]

print(rec(N,S,dp))

Submission status: Time Limit Exceeded

Solution code:
def main():
    n, k = map(int, input().split())
    s = set()
    # lr = []
    for _ in range(k):
        l, r = map(int, input().split())
        # lr.append(tuple(map(int, input().split())))
        for tmp in range(l, r+1):
            s.add(tmp)
    mod = 998244353
    
    dp = [0]*n
    dp[0] = 1
    
    for i in range(1, n):
        # for l, r in lr:
        for ss in s:
            if i-ss >= 0:
                dp[i] += dp[i-ss]
        dp[i] %= mod
    
    print(dp[-1]%mod)


main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
P=998244353
N,K=map(int,input().split())
LR=[]
for _ in range(K):
  l,r=map(int,input().split())
  LR+=range(l,r+1)
LR=list(set(LR))
LR=np.array(LR)
c=[0]*N
c[0]=1
for k in range(N):
  S=LR[LR<=k]
  while len(S):
    c[k]+=c[k-S[-1]]%P
    S=S[:-1]
print(c[-1]%P)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
import threading
import sys
import time


def get_int(): return int(stdin.readline().strip())


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


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

mod = 998244353
n,k = get_tuple()
st = list()
for _ in range(k):
    x,y = get_tuple()
    st.append([x,y])

dp = dict()
dp[0] = 1
pref_sum = 1
last_val = 0
for i in range(1,n):
    curr_sum = 0
    for x,y in st:
        if i-x>=0:
            curr_sum += dp[i-x]
        if i - y >= 1:
                curr_sum -= dp[i - y - 1]
    pref_sum += curr_sum
    last_val = curr_sum
    dp[i]=pref_sum
diff = (dp[n-1]-dp[n-2])
if diff>0:
    print(diff%mod)
else: print(0)

Submission status: Time Limit Exceeded

Solution code:

mod =998244353

N, K = map(int,input().split())

lr_list = []
for i in range(K):
    L, R = map(int,input().split())
    lr_list += list(range(L,R+1))
dp = [0]*N

min_lr_list = min(lr_list)

if min_lr_list==N:
    print(0)
else:
    dp[min_lr_list] = 1
    
    for i in range(min_lr_list+1,N):
        for j in lr_list:
            if i>j:
                dp[i] += dp[i-j]
            elif i == j:
                dp[i] += 1
    
    print(dp[-1]%mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
t = sys.stdin.readlines()
N,K = map(int, t[0].split())
S = []
for i in range(K):
    L,R = map(int, t[1+i].split())
    S += [ j for j in range(L,R+1)]

S = sorted(S)

step = [0]*(N+1)
step[1] = 1


for j in range(1,N):
    for s in S:
        if j + s > N or step[j] == 0:
            continue
        step[j+s] += step[j]
        step[j+s] %= 998244353
    
print(step[N])

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())

LR = []
for i in range(K):
    L, R = map(int, input().split())
    LR.append([L, R])
    

S = []
for lr in sorted(LR, key=lambda x:x[0]):
    S += list(range(lr[0], lr[1]+1))

dp = [0] * N
dp[0] = 1

#S.sort()

for i in range(1, N):
    for s in S:
        if i - s < 0:break
        dp[i] += dp[i - s]

print(dp[-1] % 998244353)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

mod = 998244353

n, k = map(int, input().split())

lr = [tuple(map(int, input().split())) for _ in range(k)]
lr.sort()

leaplist = []
for l, r in lr:
    leaplist += list(range(l, r + 1))
pass

dp = [0] * n
dp[0] = 1
for i in range(1, n):
    for l in leaplist:
        if i < l:
            break
        dp[i] += dp[i - l]
        dp[i] %= mod
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy

import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class Point():
    def __init__(self,y,x):
        self.x=x
        self.y=y
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    from queue import PriorityQueue
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

def to10(A):
    ret=0
    for a in range(len(A)-1,-1,-1):
        ret+=X[a]*2**(N-1-a)
    return ret
######################################################################################################
md=998244353
n,k=inputintlist()
S=[]
for a in range(k):
    l,r=inputintlist()
    for b in range(l,r+1):
        S.append(b)
dp=[0]*n
dp[0]=1
for a in range(n):
    for b in S:
        if a+b<n:
            dp[a+b]+=dp[a]
            dp[a+b]%=md
print(dp[n-1])

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
S = []
while K !=0:
    L, R = map(int, input().split())
    S += [[L,R]]
    K -= 1
A = [1]
n = 1
while n <= N - 1:
    for i in S:
        s = sum(A[n - i] for s in S for i in range(s[0], s[1] + 1) if n - i >= 0) % 998244353
        A += [s]
        s = 0
        n += 1
print(A[N-1])

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
lis = [list(map(int,input().split())) for _ in range(K)]
 
T = []
 
for i in range(K):
    for j in range(lis[i][0],lis[i][1]+1):
        T.append(j)
        if i==0:
            S = set(T)
        else:
            S = S | set(T)
    T = []
 
lis = list(S)
lis.sort()
dp  = [0]*(N+1)
dp[1] = 1
MOD = 998244353
 
for i in range(2,N+1):
    for j in lis:
        if i<=j:
            break
        else:
            dp[i] += dp[i-j]

print(dp[N]%MOD)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
L = []
R = []
for _ in range(K):
  l, r = map(int, input().split())
  L.append(l)
  R.append(r)
L.sort()
R.sort()
DP = [0] * N
DP[0] = 1

for i in range(N):
  for j in range(len(L)):
    for k in range(L[j], R[j] + 1):
      if i - k > N:
        break
      if 0 <= i - k < N:
        DP[i] += DP[i - k]
print(DP[-1]%998244353)