import heapq import math import sys readline=sys.stdin.readline class Graph: def __init__(self,V,edges=False,graph=False,directed=False,weighted=False,inf=float("inf")): self.V=V self.directed=directed self.weighted=weighted self.inf=inf if not graph: self.edges=edges self.graph=[[] for i in range(self.V)] if weighted: for i,j,d in self.edges: self.graph[i].append((j,d)) if not self.directed: self.graph[j].append((i,d)) else: for i,j in self.edges: self.graph[i].append(j) if not self.directed: self.graph[j].append(i) else: self.graph=graph self.edges=[] for i in range(self.V): if self.weighted: for j,d in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j,d)) else: for j in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j)) def Dijkstra(self,s,route_restoration=False): dist=[self.inf]*self.V dist[s]=0 hq=[(0,s)] if route_restoration: parents=[None]*self.V while hq: dx,x=heapq.heappop(hq) if dist[x]dx+dy: dist[y]=dx+dy if route_restoration: parents[y]=x heapq.heappush(hq,(dist[y],y)) if route_restoration: return dist,parents else: return dist def Route_Restoration(self,s,g,parents): route=[g] while s!=g: if parents[g]==None: route=[] break g=parents[g] route.append(g) route=route[::-1] return route def K_Shortest_Path_Routing(self,s,t,K,edge_unicursal=False,point_unicursal=False): dist,parents=self.Dijkstra(s,route_restoration=True) if dist[t]==self.inf: return False route_lst=[tuple(self.Route_Restoration(s,x,parents)) for x in range(self.V)] edges_rev=[(j,i,d) for i,j,d in self.edges] G_rev=Graph(self.V,edges=edges_rev,weighted=self.weighted,directed=self.directed,inf=self.inf) dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) route_rev_lst=[] for x in range(self.V): route=[x] while t!=x: if parents_rev[x]==None: route=[] break x=parents_rev[x] route.append(x) route_rev_lst.append(tuple(route)) route=route_lst[t] queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) bl=True if edge_unicursal: l=len(route) se=set() for j in range(len(route)-1): if self.directed: se.add((route[j],route[j+1])) else: if route[j]