Skip to content

Instantly share code, notes, and snippets.

@Kyly
Last active August 29, 2015 14:21
Show Gist options
  • Save Kyly/8392622d6893ba541034 to your computer and use it in GitHub Desktop.
Save Kyly/8392622d6893ba541034 to your computer and use it in GitHub Desktop.
from heapq import *
class vert:
def __init__(self, id):
self.id = id
self.adj = []
self.prev = None
self.dist = 0
self.dsv = 0
self.dut = 0
# self.dsu = 0
# self.dvt = 0
self.best = 0
self.visited = False
def __eq__(self, other):
return not self.id < other.id and not other.id < self.id
def __ne__(self, other):
return self.id < other.id or other.id < self.id
def __gt__(self, other):
return other.id < self.id
def __ge__(self, other):
return not self.id < other.id
def __le__(self, other):
return not other.id < self.id
def __repr__(self):
return "|{} dsv:{} dut:{}|".format(self.id, self.dsv, self.dut)
class edge:
def __init__(self, to_u, from_v, length):
self.length = length
self.to_u = to_u
self.from_v = from_v
def __repr__(self):
return "| from:{} --> To:{} length:{}|".format(self.from_v, self.to_u, self.length)
S = vert('S')
A = vert('A')
B = vert('B')
C = vert('C')
D = vert('D')
E = vert('E')
F = vert('F')
G = vert('G')
H = vert('H')
S.adj = [edge(A, S, 1), edge(C, S, 4)]
A.adj = [edge(S, A, 1), edge(B, A, 3)]
B.adj = [edge(C, B, 5), edge(A, B, 3)]
C.adj = [edge(B, C, 5), edge(S, C, 4)]
potential_edge = [edge(B,S, 4), edge(S, A, 2)]
graph = [S, A, B, C]
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Solution
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def addroad(G, s, t, E):
def setdsv(w): # Assign distances for s to v
w.dsv = w.dist
def setdut(w): # Assign distance for distance u to t
w.dut = w.dist
# Perform dijktras starting at s then starting from t
dijktras(G, s, setdsv)
dijktras(G, t, setdut)
minedge = None
mindist = float('inf')
# Iterate through potential edges
for e in E:
v = e.from_v
u = e.to_u
# Get length of path from s to t for the 2 cases
s_v_u_t = v.dsv + e.length + u.dut
s_u_v_t = u.dsv + e.length + v.dut
# Find minimum
dst = min(s_v_u_t, s_u_v_t)
# Check if a smaller option was found
if mindist > dst:
minedge = e
mindist = dst
return minedge
def dijktras(G, s, setdist):
pq = [] # Create a priority queue
# Initialize distance values and push into the heap
for v in G:
v.dist = 0 if v == s else float('inf')
heappush(pq, (v.dist, v))
while not pq == []:
_, u = heappop(pq) # Remove an element from queue
for e in u.adj:
v = e.to_u
if v.dist > u.dist + e.length:
v.dist = u.dist + e.length
setdist(v) # This assign distance to either dsu or dvt
v.prev = u
heappush(pq, (v.dist, v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment