Problem:


Score : 600 points

Problem Statement

We have N points numbered 1 to N arranged in a line in this order.

Takahashi decides to make an undirected graph, using these points as the vertices.
In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph.
The i-th operation is as follows:

The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.

The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.

Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i < R_i \leq N

1 \leq C_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 C_1
:
L_M R_M C_M

Output

Print the length of the shortest path from Vertex 1 to Vertex N in the final graph.
If there is no shortest path, print -1 instead.

Sample Input 1

4 3
1 3 2
2 4 3
1 4 6

Sample Output 1

5

We have an edge of length 2 between Vertex 1 and Vertex 2, and an edge of length 3 between Vertex 2 and Vertex 4, so there is a path of length 5 between Vertex 1 and Vertex 4.

Sample Input 2

4 2
1 2 1
3 4 2

Sample Output 2

-1

Sample Input 3

10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3

Sample Output 3

28



Sample input:
4 3
1 3 2
2 4 3
1 4 6


Sample output:
5

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 998244353
inf = float('INF')

#A
def A():
    n = II()
    n -= 1
    print(n // 2)
    return

#B
def combination_mod(n, k, mod=mod):
    """ power_funcを用いて(nCk) mod p を求める """ 
    """ nCk = n!/((n-k)!k!)を使用 """

    from math import factorial
    if n < 0 or k < 0 or n < k: return 0
    if n == 0 or k == 0: return 1
    a = factorial(n) % mod
    b = factorial(k) % mod
    c = factorial(n - k) % mod
    return (a * pow(b, mod - 2, mod) * pow(c, mod - 2, mod)) % mod
    

def B():
    n = II()
    d = LI()
    dic = defaultdict(int)
    if d[0] != 0:
        print(0)
        return
    for di in d[1:]:
        dic[di] += 1
    ans = 1
    di = list(dic.items())
    di.sort()
    if di[0][0] != 1:
        print(0)
        return
    for i in range(len(di) - 1):
        if di[i][0] != di[i + 1][0] - 1:
            print(0)
            return
    be = 1
    for _, b in di:
        ans *= pow(be, b, mod)
        be = b
        ans %= mod
    print(ans)
    return
class BinaryIndexedTree:
    # http://hos.ac/slides/20140319_bit.pdf
    def __init__(self, size):
        """
        :param int size:
        """
        self.bit = [0 for _ in range(size)]
        self.size = size

    def add(self, i, w):
        """
        i番目にwを加える
        :param int i:
        :param int w:
        :return:
        """
        x = i + 1
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        """
        [0,i]の合計
        :param int i:
        :return:
        """
        res = 0
        x = i + 1
        while x > 0:
            res += self.bit[x - 1]
            x -= x & -x
        return res

    def search(self, x):
        """
        二分探索。和がx以上となる最小のインデックス(>= 1)を返す
        :param int x:
        :return :
        """
        i = 1
        s = 0
        step = 1 << (self.size.bit_length() - 1)
        while step:
            if i + step <= self.size and s + self.bit[i + step - 1] < x:
                i += step
                s += self.bit[i - 1]
            step >>= 1
        return i

    def __len__(self):
        return self.size
#C
def C():
    n = II()
    a = LI()
    b = LI()
    tmp = [inf, inf]
    res = None
    for i in range(n):
        if tmp[0] >= b[i] - a[i] >= 0 and b[i] < tmp[1]:
            res = i
            tmp = [b[i] - a[i], b[i]]
    if res == None:
        print("No")
        return
    del a[res]
    del b[res]
    a.sort()
    b.sort()
    ans = 0
    bit = BinaryIndexedTree(b[-1] + 1)
    n -= 1
    for i in range(n):
        tmp = bisect_right(a, b[i]) - bit.sum(b[i])
        bit.add(b[i],1)
        if tmp <= 0:
            print("No")
            return
    print("Yes")

    return

from heapq import heappush, heappop

def Dijkstra(num, start, vedge):
    """ vedge は DAG の 重みとして vedge[from] = (to, value)　としておくこと """
    """ DAGでない場合は vedge[from] と vedge[to] の両方を作ること """
    """ dist[i] は start から i までの最短距離 """

    dist = [float("inf") for i in range(num)]
    dist[start] = 0
    q = [[dist[start], start]]
    while q:
        du, u = heappop(q)
        l = u
        for k, j in vedge[u]:
            for j in range(l, j + 1):
                if dist[j] > du + k:
                    dist[j] = du + k
                    heappush(q, [dist[j], j])
                    l = u
    return dist


#D
def D():
    n, m = LI()
    dist = [[] for i in range(n)]
    for _ in range(m):
        l, r, c = LI_()
        c += 1
        dist[l].append([c, r])
    for i in range(n):
        dist[i].sort()
    dist = Dijkstra(n, 0, dist)
    print(dist[n - 1] if dist[n - 1] != inf else -1)
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
LRC = [list(map(int, input().split())) for i in range(M)]
LRC = sorted(LRC)
#print(LRC)
A = [10**16] * N
A[0] = 0

for i in range(M):
  L, R, C = LRC[i][0] - 1, LRC[i][1] - 1, LRC[i][2]
  if C < A[R]:
    for j in range(L+1, R+1):
      A[j] = min(A[j], A[L] + C)

#出力
ans = A[-1]
if ans > 10 ** 15:
  ans = -1
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m = [int(v) for v in input().split(' ')]

costs = []
links = []
for i in range(n):
    costs.append([0] * i)
    links.append([])

for i in range(m):
    l, r, c = [int(v) for v in input().split(' ')]
    l -= 1
    r -= 1

    for j in range(l, r):
        for k in range(j + 1, r + 1):
            c0 = costs[k][j]
            if c0 == 0 or c0 > c:
                costs[k][j] = c
                links[k].append(j)

import heapq
h = []
closed = 0

heapq.heappush(h, (0, n-1))

while len(h) > 0:
    c0, n1 = heapq.heappop(h)
    if n1 == 0:
        print(c0)
        exit()

    for n2 in links[n1]:
        c1 = costs[n1][n2]
        heapq.heappush(h, (c0 + c1, n2))

print("-1")

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
LRC = [list(map(int, input().split())) for _ in range(M)]

graph = [[] for _ in range(N)]

for i, (Li, Ri, Ci) in enumerate(LRC):
    graph[Li - 1].append((Ri, Ci))
    for idx in range(Ri - Li):
        graph[(Ri - idx) - 1].append(((Ri - idx - 1), 0))

import heapq

inf = 10 ** 18
d = [inf] * N

q = [(0, 1)] # cost, pos
while len(q):
    cost, src = heapq.heappop(q)
    for dst, c_dst in graph[src - 1]:
        if cost + c_dst < d[dst - 1]:
            d[dst - 1] = cost + c_dst
            heapq.heappush(q, (cost + c_dst, dst))

if d[N - 1] == inf:
    print(-1)
else:
    print(d[N - 1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = list(map(int, input().split()))

edges = [list(map(int, input().split())) for _ in range(m)]
edges.sort(key = lambda x: (x[1], x[0]))

dp = np.full(n + 1, np.inf)
dp[1] = 0

for e in edges:
    dp[e[1]] = min(min(dp[e[0]:(e[1] + 1)])+ e[2], dp[e[1]])

if np.isinf(dp[-1]):
    print(-1)
else:
    print(int(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n, m = map(int, input().split())
ro = [[0 for i in range(n)] for i in range(n)]
lis = np.array([[int(i) for i in input().split(" ")] for i in range(m)])
lis = lis[lis[:,0].argsort(), :]
for i in lis:
    l, r, c = i
    for j in range(i[0]-1, i[1]-1):
        for k in range(i[0], i[1]):
            if ro[j][k] == 0:
                ro[j][k] = i[2]
                ro[k][j] = i[2]
            else:
                if ro[j][k] > i[2]:
                    ro[j][k] = i[2]
                    ro[k][j] = i[2]
             


route_list = ro

node_num = len(route_list) #ノードの数

unsearched_nodes = list(range(node_num)) # 未探索ノード
distance = [float("inf")] * node_num # ノードごとの距離のリスト
previous_nodes = [-1] * node_num # 最短経路でそのノードのひとつ前に到達するノードのリスト
distance[0] = 0 # 初期のノードの距離は0とする

def get_target_min_index(min_index, distance, unsearched_nodes):
    start = 0
    while True:
        index = distance.index(min_index, start)
        found = index in unsearched_nodes
        if found:
            return index
        else:
            start = index + 1

while(len(unsearched_nodes) != 0): #未探索ノードがなくなるまで繰り返す
    # まず未探索ノードのうちdistanceが最小のものを選択する
    posible_min_distance = float("inf") # 最小のdistanceを見つけるための一時的なdistance。初期値は inf に設定。
    for node_index in unsearched_nodes: # 未探索のノードのループ
        if posible_min_distance > distance[node_index]: 
            posible_min_distance = distance[node_index] # より小さい値が見つかれば更新
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes) # 未探索ノードのうちで最小のindex番号を取得
    unsearched_nodes.remove(target_min_index) # ここで探索するので未探索リストから除去

    target_edge = route_list[target_min_index] # ターゲットになるノードからのびるエッジのリスト
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis # 過去に設定されたdistanceよりも小さい場合はdistanceを更新
                previous_nodes[index] =  target_min_index #　ひとつ前に到達するノードのリストも更新

if distance[node_num - 1] == float("inf"):
    print(-1)
else:
    print(distance[node_num - 1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 998244353
inf = float('INF')

#A
def A():
    n = II()
    n -= 1
    print(n // 2)
    return

#B
def combination_mod(n, k, mod=mod):
    """ power_funcを用いて(nCk) mod p を求める """ 
    """ nCk = n!/((n-k)!k!)を使用 """

    from math import factorial
    if n < 0 or k < 0 or n < k: return 0
    if n == 0 or k == 0: return 1
    a = factorial(n) % mod
    b = factorial(k) % mod
    c = factorial(n - k) % mod
    return (a * pow(b, mod - 2, mod) * pow(c, mod - 2, mod)) % mod
    

def B():
    n = II()
    d = LI()
    dic = defaultdict(int)
    if d[0] != 0:
        print(0)
        return
    for di in d[1:]:
        dic[di] += 1
    ans = 1
    di = list(dic.items())
    di.sort()
    if di[0][0] != 1:
        print(0)
        return
    for i in range(len(di) - 1):
        if di[i][0] != di[i + 1][0] - 1:
            print(0)
            return
    be = 1
    for _, b in di:
        ans *= pow(be, b, mod)
        be = b
        ans %= mod
    print(ans)
    return
class BinaryIndexedTree:
    # http://hos.ac/slides/20140319_bit.pdf
    def __init__(self, size):
        """
        :param int size:
        """
        self.bit = [0 for _ in range(size)]
        self.size = size

    def add(self, i, w):
        """
        i番目にwを加える
        :param int i:
        :param int w:
        :return:
        """
        x = i + 1
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        """
        [0,i]の合計
        :param int i:
        :return:
        """
        res = 0
        x = i + 1
        while x > 0:
            res += self.bit[x - 1]
            x -= x & -x
        return res

    def search(self, x):
        """
        二分探索。和がx以上となる最小のインデックス(>= 1)を返す
        :param int x:
        :return :
        """
        i = 1
        s = 0
        step = 1 << (self.size.bit_length() - 1)
        while step:
            if i + step <= self.size and s + self.bit[i + step - 1] < x:
                i += step
                s += self.bit[i - 1]
            step >>= 1
        return i

    def __len__(self):
        return self.size
#C
def C():
    n = II()
    a = LI()
    b = LI()
    tmp = [inf, inf]
    res = None
    for i in range(n):
        if tmp[0] >= b[i] - a[i] >= 0 and b[i] < tmp[1]:
            res = i
            tmp = [b[i] - a[i], b[i]]
    if res == None:
        print("No")
        return
    del a[res]
    del b[res]
    a.sort()
    b.sort()
    ans = 0
    bit = BinaryIndexedTree(b[-1] + 1)
    n -= 1
    for i in range(n):
        tmp = bisect_right(a, b[i]) - bit.sum(b[i])
        bit.add(b[i],1)
        if tmp <= 0:
            print("No")
            return
    print("Yes")

    return

from heapq import heappush, heappop

def Dijkstra(num, start, vedge):
    """ vedge は DAG の 重みとして vedge[from] = (to, value)　としておくこと """
    """ DAGでない場合は vedge[from] と vedge[to] の両方を作ること """
    """ dist[i] は start から i までの最短距離 """

    dist = [float("inf") for i in range(num)]
    dist[start] = 0
    q = [[dist[start], start]]
    while q:
        du, u = heappop(q)
        for k, j in vedge[u]:
            for j in range(u, j + 1):
                if dist[j] > du + k:
                    dist[j] = du + k
                    heappush(q, [dist[j], j])
    return dist


#D
def D():
    n, m = LI()
    dist = [[] for i in range(n)]
    for _ in range(m):
        l, r, c = LI_()
        c += 1
        dist[l].append([c, r])
    for i in range(n):
        dist[i].sort()
    dist = Dijkstra(n, 0, dist)
    print(dist[n - 1] if dist[n - 1] != inf else -1)
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Time Limit Exceeded

Solution code:
n, m = [int(v) for v in input().split(' ')]

costs = []
links = []
for i in range(n):
    costs.append([0] * i)
    links.append([])

for i in range(m):
    l, r, c = [int(v) for v in input().split(' ')]
    l -= 1
    r -= 1

    for j in range(l, r):
        for k in range(j + 1, r + 1):
            c0 = costs[k][j]
            if c0 == 0 or c0 > c:
                costs[k][j] = c
                links[k].append(j)

import heapq
h = []
closed = 0

heapq.heappush(h, (0, n-1))

while len(h) > 0:
    c0, n1 = heapq.heappop(h)
    closed |= (1 << n1)

    if n1 == 0:
        print(c0)
        exit()

    for n2 in links[n1]:
        if closed & (1 << n2) != 0:
            continue

        c1 = 0
        if n2 < n1:
            c1 = costs[n1][n2]
#        elif n2 > n1:
#            c1 = costs[n2][n1]
#        if c1 > 0:
            heapq.heappush(h, (c0 + c1, n2))

print("-1")

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d

################################
n, m = map(int, input().split())
cost = [[float("inf") for i in range(n)] for i in range(n)]
for i in range(0, m):
    L, R, c = map(int, input().split())
    for j in range(L, R):
        for k in range(j, R):
            if cost[j - 1][k] > c:
                cost[j - 1][k] = c
result = dijkstra(0,n,m,cost)
if result[n-1] == float("inf"):
    print(-1)
else:
    print(result[n-1])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
from collections import defaultdict
N,M = map(int,input().split(' '))
g = defaultdict(list)
lmin = [N+1] * (N+1)
for i in range(1,M+1):
    l,r,c= list(map(int,input().split(' ')))
    g[l].append((r,c))
    lmin[r] = min(lmin[r], l)
for i in range(1,N+1):
    for j in range(lmin[i],i):
        g[i].append((j,0))

INF = 10**20
d = [INF] * (N+1)
d[1] = 0
que = []
heappush(que,(1,0))
while que:
    s, dist = heappop(que)
    if d[s] < dist:
        continue
    for t,c in g[s]:
        if d[t] > d[s] + c:
            d[t] = d[s] + c
            heappush(que,(t,d[t]))
if d[N] == INF:
    print(-1)
    exit()
print(d[N])

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
LRC = [list(map(int, input().split())) for i in range(M)]
LRC = sorted(LRC)
#print(LRC)
A = [10**16] * N
A[0] = 0

for i in range(M):
  L, R, C = LRC[i][0] - 1, LRC[i][1] - 1, LRC[i][2]
  if C < A[-1]:
    for j in range(L+1, R+1):
      A[j] = min(A[j], A[L] + C)

#出力
ans = A[-1]
if ans > 10 ** 15:
  ans = -1
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class SegTree:
    def __init__(self, N):
        self.N = N
        self._N = 1<<((N-1).bit_length())
        self.node = [10**15]*(2*self._N-1)
        self.node[self._N-1] = 0

    def eval(self,p):
        i = p + self._N-1
        cur = self.node[i]
        while i:
            i = (i-1) // 2
            if cur > self.node[i]:
                cur = self.node[i]
        self.node[p+self._N-1] = cur
        return cur

    def update(self,x,p,q,idx=0,a=0,b=None):
        if not idx:
            x += self.eval(p)
        if x >= 10**15:
            return
        if b is None:
            b = self._N
        if q <= p or b <= p or q <= a:
            return
        elif p <= a and b <= q:
            if x < self.node[idx]:
                self.node[idx] = x
            return
        else:
            self.update(x,p,q,idx*2+1,a,(a+b)//2)
            self.update(x,p,q,idx*2+2,(a+b)//2,b)
            return


n,m = map(int, input().split())
edge = [tuple(map(int, input().split())) for _ in range(m)]
edge.sort()
tr = SegTree(n)
for s,t,c in edge:
    tr.update(c,s-1,t)
ans = tr.eval(n-1)
if ans >= 10**15:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


class SegmentTree():
    '''
    非再帰
    segment tree
    '''

    def __init__(self, n, func, init=float('inf')):
        '''
        n->配列の長さ
        func:func(a,b)->val,　func=minだとRMQになる
        木の高さhとすると,
        n:h-1までのノード数。h段目のノードにアクセスするために使う。
        data:ノード。
        parent:k->child k*2+1とk*2+2
        '''
        self.n = 2**(n-1).bit_length()
        self.init = init
        self.data = [init]*(2*self.n)
        self.func = func

    def set(self, k, v):
        '''
        あたいの初期化
        '''
        self.data[k+self.n-1] = v

    def build(self):
        '''
        setの後に一斉更新
        '''
        for k in reversed(range(self.n-1)):
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def update(self, k, a):
        '''
        list[k]=aに更新する。
        更新ぶんをrootまで更新
        '''
        k += self.n-1
        self.data[k] = a

        while k > 0:
            k = (k-1)//2
            self.data[k] = self.func(self.data[k*2+1], self.data[k*2+2])

    def query(self, l, r):
        '''
        [l,r)のfuncを求める
        '''
        L = l+self.n
        R = r+self.n
        ret = self.init
        while L < R:
            if R & 1:
                R -= 1
                ret = self.func(ret, self.data[R-1])
            if L & 1:
                ret = self.func(ret, self.data[L-1])
                L += 1
            L >>= 1
            R >>= 1
        return ret


N, C = map(int, input().split())
L = [list(map(int, input().split())) for _ in range(C)]
L = sorted(L, key=lambda x: (x[1], -x[2], x[0]), reverse=True)

Seg = SegmentTree(N+1, func=lambda a, b: min(a, b))
Seg.set(N, 0)
Seg.build()

dist = [float("inf")]*(N+1)
dist[-1] = 0
for l, r, c in L:
    new = min(Seg.query(l, r+1)+c, Seg.query(l, l+1))
    Seg.set(l, new)
    Seg.build()
ans = Seg.query(1, 2)
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
lrc = []
for i in range(m):
    lrc.append(list(map(int, input().split())))
lrc.sort(key = lambda x: x[1])
lrc.sort()
dis = [float("inf")] * n
dis[0] = 0
for i in range(m):
    l = lrc[i][0]
    for j in range(l + 1, lrc[i][1] + 1):
        dis[j - 1] = min(dis[j - 1], dis[l - 1] + lrc[i][2])
if dis[n - 1] == float("inf"):
    print(-1)
else:
    print(dis[n - 1])

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
LRC = [list(map(int, input().split())) for i in range(M)]
LRC = sorted(LRC)
#print(LRC)
A = [10**16] * N
A[0] = 0

for i in range(M):
  L, R, C = LRC[i][0] - 1, LRC[i][1] - 1, LRC[i][2]
  for j in range(L+1, R+1):
    A[j] = min(A[j], A[L] + C)

#出力
ans = A[-1]
if ans > 10 ** 15:
  ans = -1
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m=map(int,input().split())
a=sorted([list(map(int,input().split()))for i in range(m)])
s=np.array([float("INF")]*(n+1))
s[1]=0
for i in range(m):
    if a[i][0]!=1 and s[a[i][0]]==0:
        print(-1)
        break
    else:
        s[a[i][0]:a[i][1]+1]=np.minimum(s[a[i][0]:a[i][1]+1],s[a[i][0]]+a[i][2])
if s[-1]!=float("INF"):
    print(int(s[-1]))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

N, M = list(map(int,input().split()))
LRC = [list(map(int,input().split())) for i in range(M)]
LRC.sort()

INF = 100100100100100100
dist = [INF]*N
dist[0] = 0

for li, ri, ci in LRC:
	for i in range(li,ri):
		dist[i] = min(dist[i], dist[li-1]+ci)

ans = dist[-1]
if ans==INF: ans = -1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 998244353
inf = float('INF')

#A
def A():
    n = II()
    n -= 1
    print(n // 2)
    return

#B
def combination_mod(n, k, mod=mod):
    """ power_funcを用いて(nCk) mod p を求める """ 
    """ nCk = n!/((n-k)!k!)を使用 """

    from math import factorial
    if n < 0 or k < 0 or n < k: return 0
    if n == 0 or k == 0: return 1
    a = factorial(n) % mod
    b = factorial(k) % mod
    c = factorial(n - k) % mod
    return (a * pow(b, mod - 2, mod) * pow(c, mod - 2, mod)) % mod
    

def B():
    n = II()
    d = LI()
    dic = defaultdict(int)
    if d[0] != 0:
        print(0)
        return
    for di in d[1:]:
        dic[di] += 1
    ans = 1
    di = list(dic.items())
    di.sort()
    if di[0][0] != 1:
        print(0)
        return
    for i in range(len(di) - 1):
        if di[i][0] != di[i + 1][0] - 1:
            print(0)
            return
    be = 1
    for _, b in di:
        ans *= pow(be, b, mod)
        be = b
        ans %= mod
    print(ans)
    return
class BinaryIndexedTree:
    # http://hos.ac/slides/20140319_bit.pdf
    def __init__(self, size):
        """
        :param int size:
        """
        self.bit = [0 for _ in range(size)]
        self.size = size

    def add(self, i, w):
        """
        i番目にwを加える
        :param int i:
        :param int w:
        :return:
        """
        x = i + 1
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        """
        [0,i]の合計
        :param int i:
        :return:
        """
        res = 0
        x = i + 1
        while x > 0:
            res += self.bit[x - 1]
            x -= x & -x
        return res

    def search(self, x):
        """
        二分探索。和がx以上となる最小のインデックス(>= 1)を返す
        :param int x:
        :return :
        """
        i = 1
        s = 0
        step = 1 << (self.size.bit_length() - 1)
        while step:
            if i + step <= self.size and s + self.bit[i + step - 1] < x:
                i += step
                s += self.bit[i - 1]
            step >>= 1
        return i

    def __len__(self):
        return self.size
#C
def C():
    n = II()
    a = LI()
    b = LI()
    tmp = [inf, inf]
    res = None
    for i in range(n):
        if tmp[0] >= b[i] - a[i] >= 0 and b[i] < tmp[1]:
            res = i
            tmp = [b[i] - a[i], b[i]]
    if res == None:
        print("No")
        return
    del a[res]
    del b[res]
    a.sort()
    b.sort()
    ans = 0
    bit = BinaryIndexedTree(b[-1] + 1)
    n -= 1
    for i in range(n):
        tmp = bisect_right(a, b[i]) - bit.sum(b[i])
        bit.add(b[i],1)
        if tmp <= 0:
            print("No")
            return
    print("Yes")

    return

from heapq import heappush, heappop

def Dijkstra(num, start, vedge):
    """ vedge は DAG の 重みとして vedge[from] = (to, value)　としておくこと """
    """ DAGでない場合は vedge[from] と vedge[to] の両方を作ること """
    """ dist[i] は start から i までの最短距離 """

    dist = [float("inf") for i in range(num)]
    dist[start] = 0
    q = [[dist[start], start]]
    while q:
        du, u = heappop(q)
        for j, k in vedge[u]:
            for j in range(u, j + 1):
                if dist[j] > du + k:
                    dist[j] = du + k
                    heappush(q, [dist[j], j])
    return dist


#D
def D():
    n, m = LI()
    dist = [[] for i in range(n)]
    for _ in range(m):
        l, r, c = LI_()
        c += 1
        dist[l].append((r, c))
    dist = Dijkstra(n, 0, dist)
    print(dist[n - 1] if dist[n - 1] != inf else -1)
    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Time Limit Exceeded

Solution code:

N, M =map(int, input().split())
node_num = N
route_list  = [[0 for i in range(N)] for j in range(N)]

for i in range(M):
    l,r,c = map(int, input().split())
    for k in range(l,r):
      for j in range(k+1,r+1):

        if route_list[k-1][j-1] == 0:
          route_list[k-1][j-1] = c
          route_list[j-1][k-1] = c
        else:
          route_list[k-1][j-1] = min(route_list[k-1][j-1],c)
          route_list[j-1][k-1] = min(route_list[j-1][k-1],c)

unsearched_nodes = list(range(node_num)) 
distance = [float('inf')] * node_num 
previous_nodes = [-1] * node_num
distance[0] = 0

def get_target_min_index(min_index, distance, unsearched_nodes):
    start = 0
    while True:
        index = distance.index(min_index, start)
        found = index in unsearched_nodes
        if found:
            return index
        else:
            start = index + 1
while(len(unsearched_nodes) != 0): #未探索ノードがなくなるまで繰り返す
    # まず未探索ノードのうちdistanceが最小のものを選択する
    posible_min_distance =float('inf') # 最小のdistanceを見つけるための一時的なdistance。初期値は inf に設定。
    for node_index in unsearched_nodes: # 未探索のノードのループ
        if posible_min_distance > distance[node_index]: 
            posible_min_distance = distance[node_index] # より小さい値が見つかれば更新
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes) # 未探索ノードのうちで最小のindex番号を取得
    unsearched_nodes.remove(target_min_index) # ここで探索するので未探索リストから除去

    target_edge = route_list[target_min_index] # ターゲットになるノードからのびるエッジのリスト
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis # 過去に設定されたdistanceよりも小さい場合はdistanceを更新
                previous_nodes[index] =  target_min_index #　ひとつ前に到達するノードのリストも更新
#print("-----経路-----")
previous_node = node_num - 1
"""
while previous_node != -1:
    if previous_node !=0:
        print(str(previous_node + 1) + " <- ", end='')
    else:
        print(str(previous_node + 1))
    previous_node = previous_nodes[previous_node]
"""
#print("-----距離-----")
if distance[node_num - 1] ==float('inf'):
  print(-1)
else:
  print(distance[node_num - 1])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
lst = []
for i in range(m):
    lsti = list(map(int, input().split()))
    lst.append(lsti)

lst.sort(key= lambda x: x[2], reverse=True)
lst.sort(key= lambda x: x[0])

d = [10**18 for i in range(n+1)]
d[1] = 0
for lsti in lst:
    l = lsti[0]
    r = lsti[1]
    c = lsti[2]
    if l == 1:
        for i in range(l+1, r+1):
            d[i] = c
    else:
        for i in range(l+1, r+1):
            d[i] = min(d[i], d[l]+c)

if d[n] == 10**18:
    print(-1)
else:
    print(d[n])