Problem:


Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

3 2 5
1 2 3
2 3 3
2
3 2
1 3

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

5 4 4
1 2 2
2 3 2
3 4 3
4 5 2
20
2 1
3 1
4 1
5 1
1 2
3 2
4 2
5 2
1 3
2 3
4 3
5 3
1 4
2 4
3 4
5 4
1 5
2 5
3 5
4 5

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0



Sample input:
3 2 5
1 2 3
2 3 3
2
3 2
1 3


Sample output:
0
1

Submission status: Time Limit Exceeded

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        #self.st=SegTree(self.size*2-1,self.ETdepth,function=min,ide=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in edge]) for edge in self.edges]):
            print( [[nd for nd,d in edge] for edge in self.edges] )
        else:
            print(self)
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    # return boundary index of r such that func({table[i]} =< x , i in [pos,r]
    def right_bound(self,pos,x):
        k=(self.size-pos).bit_length()
        for j in range(k)[::-1]:
            nx=pos+(1<<j)
            if nx<n and self.query(pos,nx+1)<=x:
                pos+=(1<<j)
        return pos
    
    # return boundary index of l such that func({table[i]} =< x , i in [l,pos]
    def left_bound(self,pos,x):
        k=pos.bit_length()
        for j in range(k)[::-1]:
            nx=pos-(1<<j)
            if 0<=nx and self.query(nx,pos+1)<=x:
                pos-=(1<<j)
        return pos
 
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)

def dijkstra(edge,st):
    # edge=[[(v_to,dist_to_v),...],[],...]
    # initialize: def: d=dist(st,i), prev=[previous vertex in minimum path], q[]
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    prev=[0]*n
    q=[(j,i) for i,j in enumerate(d)]
    heapify(q)
    v=[False]*n
    # calc
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for dst,dist in edge[cur]:
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                prev[dst]=cur
                heappush(q,(alt,dst))
    return d,prev


show_flg=False
show_flg=True
ans=0

n,m,l=LI()
e_gas,_=GI(n,m)

d_gas=[]
g=[[]for i in rep(n)]
for i in rep(n):
    d,_=dijkstra(e_gas,i)
    for j in rep(i+1,n):
        if d[j]<=l:
            g[i]+=(j,1),
            g[j]+=(i,1),
            

#show(g);exit()

dist=[]
for i in rep(n):
    d,_=dijkstra(g,i)
    dist+=[d]

#show(dist)
q=I()
for i in rep(q):
    s,t=LI_()
    ans=dist[s][t]-1
    if ans==inf:
        ans=-1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def MAP(): return map(int, input().split())
def LIST(): return list(MAP())
 
N, M, L = MAP()
edges = [[] for _ in range(N)]
for i in range(M):
    a, b, c = MAP()
    if c > L:
        continue
    edges[a - 1].append([b - 1, c])
    edges[b - 1].append([a - 1, c])
def min_select(l):
    min_index = 0
    min_val = l[0][1]
    min_fuel = l[0][2]
    for i in range(1, len(l)):
        if min_val > l[i][1]:
            min_val = l[i][1]
            min_fuel = l[i][2]
            min_index = i
        elif min_val == l[i][1]:
            if min_fuel > l[i][2]:
                min_fuel = l[i][2]
                min_index = i
    return min_index

def dijkstra(start):
    count = [-1 for _ in range(N)]
    l = [(start, 0, 0)]
    while l:
        min_index = min_select(l)
        v, c, f = l.pop(min_index)
        if count[v] != -1:
            continue
        count[v] = c
        for e in edges[v]:
            if e[0] == v:
                continue
            if e[1] + f > L:
                l.append((e[0], c + 1, e[1]))
            else:
                l.append((e[0], c, e[1] + f))
            
    return count

Q = int(input())
res = [[-1 for _ in range(N)] for _ in range(N)]
answer = [-1] * Q
executed = [False] * N
for i in range(Q):
    q1, q2 = MAP()
    start, goal = min(q1, q2) - 1, max(q1, q2) - 1
    if executed[start]:
        answer[i] = res[start][goal]
    else:
        res[start] = dijkstra(start)
        answer[i] = res[start][goal]
        executed[start] = True
for ans in answer:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def MAP(): return map(int, input().split())
def LIST(): return list(MAP())
 
N, M, L = MAP()
edges = [[] for _ in range(N)]
for i in range(M):
    a, b, c = MAP()
    if c > L:
        continue
    edges[a - 1].append([b - 1, c])
    edges[b - 1].append([a - 1, c])
def min_select(l):
    min_index = 0
    min_val = l[0][1]
    min_fuel = l[0][2]
    for i in range(1, len(l)):
        if min_val > l[i][1]:
            min_val = l[i][1]
            min_fuel = l[i][2]
            min_index = i
        elif min_val == l[i][1]:
            if min_fuel > l[i][2]:
                min_fuel = l[i][2]
                min_index = i
    return min_index

def dijkstra(start):
    count = [-1 for _ in range(N)]
    l = [(start, 0, 0)]
    while l:
        min_index = min_select(l)
        v, c, f = l.pop(min_index)
        if count[v] != -1:
            continue
        count[v] = c
        for e in edges[v]:
            if e[0] == v:
                continue
            if e[1] + f > L:
                l.append((e[0], c + 1, e[1]))
            else:
                l.append((e[0], c, e[1] + f))
            
    return count

Q = int(input())
res = []
answer = [-1] * (Q)
for i in range(Q):
    q1, q2 = MAP()
    answer[i] = dijkstra(q1 - 1)[q2 - 1]
for ans in answer:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def MAP(): return map(int, input().split())
def LIST(): return list(MAP())
 
N, M, L = MAP()
edges = [[] for _ in range(N)]
for i in range(M):
    a, b, c = MAP()
    if c > L:
        continue
    edges[a - 1].append([b - 1, c])
    edges[b - 1].append([a - 1, c])
def min_select(l):
    min_index = 0
    min_val = l[0][1]
    min_fuel = l[0][2]
    for i in range(1, len(l)):
        if min_val > l[i][1]:
            min_val = l[i][1]
            min_fuel = l[i][2]
            min_index = i
        elif min_val == l[i][1]:
            if min_fuel > l[i][2]:
                min_fuel = l[i][2]
                min_index = i
    return min_index

def dijkstra(start):
    count = [-1 for _ in range(N)]
    l = [(start, 0, 0)]
    while l:
        min_index = min_select(l)
        v, c, f = l.pop(min_index)
        if count[v] != -1:
            continue
        count[v] = c
        for e in edges[v]:
            if e[0] == v:
                continue
            if e[1] + f > L:
                l.append((e[0], c + 1, e[1]))
            else:
                l.append((e[0], c, e[1] + f))
            
    return count

Q = int(input())
q = []
answer = [[-1] * N for _ in range(N)]
for i in range(Q):
    q1, q2 = MAP()
    q.append([q1 - 1, q2 - 1])
for i in range(N):
    answer[i] = dijkstra(i)
for item in q:
    print(answer[item[0]][item[1]])

Submission status: Time Limit Exceeded

Solution code:
def MAP(): return map(int, input().split())
def LIST(): return list(MAP())
 
N, M, L = MAP()
edges = [[] for _ in range(N)]
for i in range(M):
    a, b, c = MAP()
    if c > L:
        continue
    edges[a - 1].append([b - 1, c])
    edges[b - 1].append([a - 1, c])
def min_select(l):
    min_index = 0
    min_val = l[0][1]
    min_fuel = l[0][2]
    for i in range(1, len(l)):
        if min_val > l[i][1]:
            min_val = l[i][1]
            min_fuel = l[i][2]
            min_index = i
        elif min_val == l[i][1]:
            if min_fuel > l[i][2]:
                min_fuel = l[i][2]
                min_index = i
    return min_index

def dijkstra(start):
    count = [float('inf') for _ in range(N)]
    l = [(start, 0, 0)]
    while l:
        min_index = min_select(l)
        v, c, f = l.pop(min_index)
        if count[v] < float('inf'):
            continue
        count[v] = c
        for e in edges[v]:
            if e[0] == v:
                continue
            if e[1] + f > L:
                l.append((e[0], c + 1, e[1]))
            else:
                l.append((e[0], c, e[1] + f))
            
    return count

Q = int(input())
q = []
answer = [[float('inf')] * N for _ in range(N)]
for i in range(Q):
    q1, q2 = MAP()
    q.append([q1 - 1, q2 - 1])
for i in range(N):
    answer[i] = dijkstra(i)
for item in q:
    if answer[item[0]][item[1]] == float('inf'):
        print(-1)
    else:
        print(answer[item[0]][item[1]])

Submission status: Time Limit Exceeded

Solution code:
def MAP(): return map(int, input().split())
def LIST(): return list(MAP())
 
N, M, L = MAP()
edges = [[] for _ in range(N)]
for i in range(M):
    a, b, c = MAP()
    if c > L:
        continue
    edges[a - 1].append([b - 1, c])
    edges[b - 1].append([a - 1, c])
def min_select(l):
    min_index = 0
    min_val = l[0][1]
    min_fuel = l[0][2]
    for i in range(1, len(l)):
        if min_val > l[i][1]:
            min_val = l[i][1]
            min_fuel = l[i][2]
            min_index = i
        elif min_val == l[i][1]:
            if min_fuel > l[i][2]:
                min_fuel = l[i][2]
                min_index = i
    return min_index

def dijkstra(start):
    count = [float('inf') for _ in range(N)]
    fuel = [float('inf') for _ in range(N)]
    confirm = [False for  _ in range(N)]
    l = [(start, 0, 0)]
    while l:
        min_index = min_select(l)
        v, c, f = l.pop(min_index)
        if confirm[v]:
            continue
        count[v], fuel[v] = c, f
        confirm[v] = True
        for e in edges[v]:
            if confirm[e[0]] or e[0] == v:
                continue
            if e[1] + f > L:
                l.append((e[0], c + 1, e[1]))
            else:
                l.append((e[0], c, e[1] + f))
            
    return count

Q = int(input())
q = []
answer = [[float('inf')] * N for _ in range(N)]
for i in range(Q):
    q1, q2 = MAP()
    q.append([q1 - 1, q2 - 1])
for i in range(N):
    answer[i] = dijkstra(i)
for item in q:
    if answer[item[0]][item[1]] == float('inf'):
        print(-1)
    else:
        print(answer[item[0]][item[1]])

Submission status: Time Limit Exceeded

Solution code:
inf = 10 ** 13

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

d = [[inf] * n for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    d[a - 1][b - 1] = d[b - 1][a - 1] = c
for k in range(n):
    for i in range(n):
        for j in range(n):
            d[i][j] = min(d[i][j], d[i][k] + d[k][j])

e = [[1 if d[i][j] <= l else inf for j in range(n)] for i in range(n)]
for k in range(n):
    for i in range(n):
        for j in range(n):
            e[i][j] = min(e[i][j], e[i][k] + e[k][j])

q = int(input())
for _ in range(q):
    s, t = map(int, input().split())
    a = e[s - 1][t - 1]
    print(a - 1 if a < inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
input = sys.stdin.readline
 
def main():
    n,w,l = map(int,input().split())
    g = [[] for _ in range(n)]
    for _ in range(w):
        x,y,z = map(int,input().split())
        x -= 1
        y -= 1
        if z > l:
            continue
        g[x].append((y,z))
        g[y].append((x,z))
    q = int(input())
    st = []
    for _ in range(q):
        s,t = map(int,input().split())
        s -= 1
        t -= 1
        st.append((s,t))
    d = [[] for _ in range(n)]
    for i in range(n):
        que = []
        dd = [10**15 for _ in range(n)]
        dd[i] = 0
        heappush( que,(0,i) )
        while que:
            p = heappop(que)
            v = p[1]
            if dd[v] < p[0]:
                continue
            for j in range(len(g[v])):
                edge = g[v][j]
                if dd[edge[0]] > dd[v] + edge[1]:
                    dd[edge[0]] = dd[v] + edge[1]
                    heappush( que,(dd[edge[0]] , edge[0]) )
        d[i] = dd
    G = [[10**15 for _ in range(n)] for _ in range(n)]
    for i in range(n-1):
        for j in range(i+1,n):
            if d[i][j] <= l:
                G[i][j] = 1
                G[j][i] = 1
    for i in range(n):
        G[i][i] = 0
    for k in range(n):
        for i in range(n):
            for j in range(n):
                G[i][j] = min(G[i][j],G[i][k] + G[k][j])
    for i in range(q):
        [s,t] = st[i]
        ans = G[s][t]
        if ans == 10**15:
            print(-1)
            continue
        print(ans-1)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
E - Travel by Car
https://atcoder.jp/contests/abc143/tasks/abc143_e

"""
import sys


def warshall_floyd(d, V):
    for k in range(V):
        for i in range(V):
            for j in range(V):
                new_cost = d[i][k] + d[k][j]
                if new_cost < d[i][j]:
                    d[i][j] = new_cost

def main(args):
    N, M, L = map(int, input().split())
    g1 = [[float('inf')] * (N+1) for _ in range(N+1)]
    for i in range(N+1):
        g1[i][i] = 0
    for _ in range(M):
        A, B, C = map(int, input().split())
        g1[A][B] = g1[B][A] = C
    warshall_floyd(g1, N+1)

    g2 = [[float('inf')] * (N+1) for _ in range(N+1)]
    for i in range(N+1):
        for j in range(N+1):
            if i == j:
                g2[i][j] = 0
            elif g1[i][j] <= L:
                g2[i][j] = g2[j][i] = 1
    warshall_floyd(g2, N+1)
    Q = int(input())
    for _ in range(Q):
        s, t = map(int, input().split())
        print(-1 if g2[s][t] == float('inf') else g2[s][t] - 1)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

if __name__ == '__main__':
    n, m, l = map(int, stdin.readline().rstrip().split())

    import heapq
    g = dict()
    for i in range(n):
        g[i] = []
    for _ in range(m):
        a, b, c = map(int, stdin.readline().rstrip().split())
        if c <= l:
            g[a-1].append((b-1, c))
            g[b-1].append((a-1, c))

    ans = []
    for start in range(n):
        mins1 = [10 ** 9 + 1] * n # a
        mins2 = [0] * n # n

        mins1[start], mins2[start] = 0, l

        q = [(0, l, start)] # added, left_gas, pos
        heapq.heapify(q)

        while q:
            a, b, u = heapq.heappop(q)

            if (a > mins1[u]) or (a == mins1[u] and b < mins2[u]):
                continue

            for v, weight in g[u]:
                if weight > b:
                    a_new = a + 1
                    b_new = l - weight
                else:
                    a_new = a
                    b_new = b - weight

                if a_new < mins1[v] or (a_new == mins1[v] and b_new > mins2[v]):
                    mins1[v], mins2[v] = a_new, b_new
                    heapq.heappush(q, (a_new, b_new, v))

        ans.append(mins1)

    qq = int(stdin.readline().rstrip())
    for _ in range(qq):
        s, t = map(int, stdin.readline().rstrip().split())
        tmp = ans[s-1][t-1]
        if tmp == 10 ** 9 + 1:
            print(-1)
        else:
            print(tmp)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

if __name__ == '__main__':
    n, m, l = map(int, stdin.readline().rstrip().split())

    from collections import defaultdict
    import heapq
    g = defaultdict(list)
    for _ in range(m):
        a, b, c = map(int, stdin.readline().rstrip().split())
        if c <= l:
            g[a-1].append((b-1, c))
            g[b-1].append((a-1, c))

    ans = [[0] * n for _ in range(n)]
    for start in range(n):
        mins = [[float('inf'), 0] for _ in range(n)] # (a, b)
        mins[start] = [0, l]

        q = [(0, l, start)] # added, left_gas, pos
        heapq.heapify(q)

        while q:
            a, b, u = heapq.heappop(q)

            if (a > mins[u][0]) or (a == mins[u][0] and b < mins[u][1]):
                continue

            for v, weight in g[u]:
                if weight > b:
                    a_new = a + 1
                    b_new = l - weight
                else:
                    a_new = a
                    b_new = b - weight

                if a_new < mins[v][0] or (a_new == mins[v][0] and b_new > mins[v][1]):
                    mins[v][0], mins[v][1] = a_new, b_new
                    heapq.heappush(q, (a_new, b_new, v))

        ans[start] = [_mins[0] for _mins in mins]

    qq = int(stdin.readline().rstrip())
    for _ in range(qq):
        s, t = map(int, stdin.readline().rstrip().split())
        tmp = ans[s-1][t-1]
        if tmp == float('inf'):
            print(-1)
        else:
            print(tmp)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

if __name__ == '__main__':
    n, m, l = map(int, stdin.readline().rstrip().split())

    from collections import defaultdict
    import heapq
    g = defaultdict(list)
    for _ in range(m):
        a, b, c = map(int, stdin.readline().rstrip().split())
        g[a-1].append((b-1, c))
        g[b-1].append((a-1, c))

    ans = [[0] * n for _ in range(n)]
    for start in range(n):
        mins = [[float('inf'), 0] for _ in range(n)] # (a, b)
        mins[start] = [0, l]

        q = [(0, l, start)] # added, left_gas, pos
        heapq.heapify(q)

        while q:
            a, b, u = heapq.heappop(q)

            if (a > mins[u][0]) or (a == mins[u][0] and b < mins[u][1]):
                continue

            for v, weight in g[u]:
                if weight > l:
                    continue

                if weight > b:
                    a_new = a + 1
                    b_new = l - weight
                else:
                    a_new = a
                    b_new = b - weight

                if a_new < mins[v][0] or (a_new == mins[v][0] and b_new > mins[v][1]):
                    mins[v][0], mins[v][1] = a_new, b_new
                    heapq.heappush(q, (a_new, b_new, v))

        ans[start] = [_mins[0] for _mins in mins]

    qq = int(stdin.readline().rstrip())
    for _ in range(qq):
        s, t = map(int, stdin.readline().rstrip().split())
        tmp = ans[s-1][t-1]
        if tmp == float('inf'):
            print(-1)
        else:
            print(tmp)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

if __name__ == '__main__':
    n, m, l = map(int, stdin.readline().rstrip().split())
    abc = [list(map(int, stdin.readline().rstrip().split())) for _ in range(m)]
    q = int(stdin.readline().rstrip())
    st = [list(map(int, stdin.readline().rstrip().split())) for _ in range(q)]

    from collections import defaultdict
    import heapq
    g = defaultdict(list)
    for a, b, c in abc:
        g[a-1].append((b-1, c))
        g[b-1].append((a-1, c))

    ans = [[0] * n for _ in range(n)]
    for start in range(n):
        mins = [[float('inf'), 0] for _ in range(n)] # (a, b)
        mins[start] = [0, l]

        q = [(0, l, start)] # added, left_gas, pos
        heapq.heapify(q)

        while q:
            a, b, u = heapq.heappop(q)

            if (a > mins[u][0]) or (a == mins[u][0] and b < mins[u][1]):
                continue

            for v, weight in g[u]:
                if weight > l:
                    continue

                if weight > b:
                    a_new = a + 1
                    b_new = l - weight
                else:
                    a_new = a
                    b_new = b - weight

                if a_new < mins[v][0] or (a_new == mins[v][0] and b_new > mins[v][1]):
                    mins[v][0], mins[v][1] = a_new, b_new
                    heapq.heappush(q, (a_new, b_new, v))

        ans[start] = [_mins[0] for _mins in mins]

    for s, t in st:
        tmp = ans[s-1][t-1]
        if tmp == float('inf'):
            print(-1)
        else:
            print(tmp)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

if __name__ == '__main__':
    n, m, l = map(int, stdin.readline().rstrip().split())
    abc = [list(map(int, stdin.readline().rstrip().split())) for _ in range(m)]
    q = int(stdin.readline().rstrip())
    st = [list(map(int, stdin.readline().rstrip().split())) for _ in range(q)]

    from collections import defaultdict
    import heapq
    g = defaultdict(list)
    for a, b, c in abc:
        g[a-1].append((b-1, c))
        g[b-1].append((a-1, c))

    ans = []
    for start in range(n):
        mins = [[float('inf'), 0] for _ in range(n)] # (a, b)
        mins[start] = [0, l]

        q = [(0, l, start)] # added, left_gas, pos
        heapq.heapify(q)

        while q:
            a, b, u = heapq.heappop(q)

            if (a > mins[u][0]) or (a == mins[u][0] and b < mins[u][1]):
                continue

            for v, weight in g[u]:
                if weight > l:
                    continue

                if weight > b:
                    a_new = a + 1
                    b_new = l - weight
                else:
                    a_new = a
                    b_new = b - weight

                if a_new < mins[v][0] or (a_new == mins[v][0] and b_new > mins[v][1]):
                    mins[v][0], mins[v][1] = a_new, b_new
                    heapq.heappush(q, (a_new, b_new, v))

        ans.append([_mins[0] for _mins in mins])

    for s, t in st:
        tmp = ans[s-1][t-1]
        if tmp == float('inf'):
            print(-1)
        else:
            print(tmp)