def f(): with open("q1.txt","r") as read: line = read.readline() x,y = line.split() #print "badfa" while(x != '-1' and y != '-1'): hd = heapdict() line = read.readline().replace('-',' ').replace(':',' ').replace(' ',' ').split() data={} j = 0 print line while(j != len(line)): data[int(line[j]),int(line[j+1])]=int(line[j+2]) j+=3 hd[0]=0 for i in range(1,int(x)): hd[i]=sys.maxint rl = ff(hd,data,x) if rl != sys.maxint: print rl else: print "no answer" x,y = read.readline().split()
def shortest(n, _edges): edges = defaultdict(list) for (u, v, cost) in _edges: # undirected edges[u].append((v, cost)) edges[v].append((u, cost)) dist = defaultdict(lambda: float('inf')) dist[0] = 0 print "dist: ", dist prevnode = defaultdict(lambda: -1) prevnode[0] = -1 unvisited = heapdict() unvisited[0] = 0 for i in range(1, n - 1): unvisited[i] = float('inf') #print "len: ", len(unvisited) current = 0 for j in range(n - 1): current, d = unvisited.popitem() #print "current: ", current, "d:", d for i, (v, c) in enumerate(edges[current]): print "current: ", current, "v: ", v ans = dist[current] + c if ans < dist[v]: print "changing best[v]: ", dist[ v], "current: ", current, "v: ", v dist[v] = ans prevnode[v] = current unvisited[v] = ans return dist[n - 1], solution(prevnode, n - 1)
def f(): with open("q1.txt","r") as read: line = read.readline() x,y = line.split() while(x != '-1' and y != '-1'): hd = heapdict() line = read.readline().replace('-',' ').replace(':',' ').replace(' ',' ').split() data={} i = 0 while i != len(line): data[int(line[i]),int(line[i+1])] = int(line[i+2]) i+=3 #print line print data color ={} hd[0]=0 color[0]='b' p={} for j in range(1,int(x)): hd[j]=sys.maxint color[j]='w' ff(hd,data,x,p,color) if len(p)==int(x)-1: print x, for i in p: print "%s%s%s%s%s" %(p[i],'-',i,':',data[p[i],i]), else: print "NO SPANNING TREE" print '' x,y = read.readline().split()
def f(): with open("q1.txt","r") as read: line = read.readline() x,y = line.split() #print "badfa" while(x != '-1' and y != '-1'): hd = heapdict() line = read.readline().replace('-',' ').replace(':',' ').replace(' ',' ').split() data={} j = 0 print line while(j != len(line)): data[int(line[j]),int(line[j+1])]=int(line[j+2]) hd[int(line[j]),int(line[j+1])] = int(line[j+2]) j+=3 print data color = [] #assign color to each v for i in range(int(x)): color.append(i) ff(data,hd,color) x,y = read.readline().split()
def shortest(n, a): edges = defaultdict(list) nodes = heapdict() back = defaultdict(int) for x in a: edges[x[0]].append((x[1], x[2])) edges[x[1]].append((x[0], x[2])) ''' for i in range(n): # nodes.__setitem__(i,float('inf')) back[i] = -1 ''' visited = set() # nodes[0] = 0 def _shortest(currentNode, v): visited.add(currentNode) if currentNode == n - 1: return v for un, volueOfun in edges[currentNode]: if un in visited: continue ''' if x[0] not in nodes.__iter__(): nodes.__setitem__(x[0], float('inf')) ''' ''' un = x[0] volueOfun = v + x[1] ''' newvValueOfun = volueOfun + v ''' un = nodes.__getitem__(x[0]) ''' if (un not in nodes.keys()) or (newvValueOfun < nodes[un]): nodes[un] = newvValueOfun back[un] = currentNode # print(nodes.__iter__()) if len(nodes) == 0: return None nextNode, nextNodeV = nodes.popitem() return _shortest(nextNode, nextNodeV) def traceback(currentNode): if currentNode == 0: return [0] return traceback(back[currentNode]) + [currentNode] # t = nodes.popitem() optV = _shortest(0, 0) if optV is None: return None return (optV, traceback(n - 1))
def dijkstra(graph, capacity, V, src, dest): dist, visited, queue = [float("inf")] * V, [0] * V, heapdict() queue[src], dist[src], visited[src] = 0, 0, True while queue: u, _ = queue.popitem() # pop vertex with min distance visited[u] = True for v in graph[u]: if not visited[v]: queue[v] = dist[v] = min(dist[v], dist[u] + capacity[u, v]) print dist[dest] if dist[dest] < float("inf") else "UNREACHABLE"
def shortest(n, a): edges = defaultdict(list) nodes = heapdict() back = defaultdict(int) for x in a: if x[0] not in edges: edges[x[0]] = [] edges[x[0]].append((x[1], x[2])) edges[x[1]].append((x[0], x[2])) # print(edges[x[0]]) for i in range(n): nodes.__setitem__(i, float('inf')) back[i] = -1 visited = [] nodes.__setitem__(1760, 0) # print(edges, nodes) ''' for x in range(n): print(edges[x]) ''' def _shortest(currentNode, v): visited.append(currentNode) # print(currentNode) if currentNode == 669: return v for x in edges[currentNode]: if x[0] in visited: continue vn = v un = nodes.__getitem__(x[0]) # print(vn, un) if x[1] + vn < un: nodes.__setitem__(x[0], x[1] + vn) back[x[0]] = currentNode # print(x[0], x[1] + vn) # nodes.__delitem__(currentNode) nextNode, nextNodeV = nodes.popitem() # print(nextNodeV) return _shortest(nextNode, nextNodeV) def traceback(currentNode): if currentNode == 1760: return [1760] return traceback(back[currentNode]) + [currentNode] nodes.popitem() optV = _shortest(1760, 0) res = traceback(669) return (optV, res)
def dijkstra(num_vertices, graph, source): distances = [0 for i in range(num_vertices)] vertex_set = heapdict() for i in range(1, num_vertices + 1): if source != i: distances[i - 1] = float('inf') vertex_set[i] = distances[i - 1] while len(vertex_set) > 0: u = vertex_set.popitem() for neighbor_edge in graph[u[0] - 1]: alt = distances[u[0] - 1] + neighbor_edge[2] if alt < distances[neighbor_edge[1] - 1]: distances[neighbor_edge[1] - 1] = alt vertex_set[neighbor_edge[1]] = alt return distances
def prim(graph, capacity, V, src, dest): dist, visited, prev = [float('inf')]*V, [0]*V, [-1]*V queue, edges = heapdict(), set() min_weight, queue[src], dist[src], visited[src] = 0, 0, 0, True while queue: u, weight = queue.popitem() visited[u] = True if weight: min_weight, (_u, _v) = min_weight + weight, min( (prev[u], u), (u, prev[u])) edges.add( (str(_u) + '-' + str(_v) + ':' + str(weight)) ) for v in graph[u]: if not visited[v]: dist[v], prev[v] = min( (dist[v], prev[v]), (capacity[u, v], u)) queue[v] = dist[v] if len(edges) < dest: print 'NO SPANNING TREE' else: print min_weight, ' '.join(sorted(edges))
def shortest(n, paths): # v = range(n) hd = heapdict() back = [0] res = [float("inf")] * n for i in range(n): hd[i] = float("inf") idx = 0 value = 0 dflag = 0 count = 0 while count != n - 1: #print idx for j in range(len(paths)): #print j if idx == paths[j][0]: tmp = value + paths[j][2] #print tmp if hd[paths[j][1]] > tmp: hd[paths[j][1]] = tmp paths[j] = (-1, -1, -1) #mark used as (-1,-1,-1) dflag = 1 #print paths if dflag: #print paths p_tmp = set(paths) p_tmp.remove((-1, -1, -1)) paths[:] = list(p_tmp) dflag = 0 idx, value = hd.popitem() #print idx, value res[idx] = value back.append(idx) count += 1 return res[n - 1], back
def dijsktra(g, src, unvisited_homes ): # src: vertex id, unvisited_homes: list of vertices ids edgeTo = {} distTo = heapdict() distDict = {} visited = {} for node in g.vet_list.keys(): distDict[node] = sys.maxsize distTo[node] = sys.maxsize visited[node] = False distDict[src] = 0 distTo[src] = 0 edgeTo[src] = None visited[src] = True v = src while distTo.peekitem()[0] not in unvisited_homes: distTo.popitem() for i in g.getVertexNeighbor(v): if visited[i]: continue else: new_dist = distDict[v] + g.getEdgelen(v, i) if new_dist < distDict[i]: distDict[i] = new_dist distTo[i] = new_dist edgeTo[i] = v v = distTo.peekitem()[0] visited[v] = True home = distTo.popitem()[0] path = [] total_weight = 0 while edgeTo[home] is not None: path.append(home) total_weight += g.getEdgelen(home, edgeTo[home]) home = edgeTo[home] path.append(home) return path, total_weight
def dijkstra(num_vertices, edges, source): graph = [[] for i in range(num_vertices)] for edge in edges: graph[edge[0] - 1].append(edge) distances = [0 for i in range(num_vertices)] vertex_set = heapdict() for i in range(1, num_vertices + 1): if source != i: distances[i - 1] = float('inf') vertex_set[i] = distances[i - 1] #heappush(vertex_set, (distances[i - 1], i)) while len(vertex_set) > 0: u = vertex_set.popitem() for neighbor_edge in graph[u[0] - 1]: alt = distances[u[0] - 1] + neighbor_edge[2] #print(alt) if alt < distances[neighbor_edge[1] - 1]: distances[neighbor_edge[1] - 1] = alt vertex_set[neighbor_edge[1]] = alt return distances
def prims(g, starting_car_location): mst = Graph() visited = [] unvisited_homes = [ node for node in g.vet_list.keys() if g.getVertex(node).isHome() ] distTo = heapdict() edgeTo = {} mst.addVertex(starting_car_location) mst.getVertex(starting_car_location).makeSrc() visited.append(starting_car_location) if g.getVertex(starting_car_location).isHome(): mst.getVertex(starting_car_location).makeHome() unvisited_homes.remove(starting_car_location) for home in unvisited_homes: distTo[home] = sys.maxsize edgeTo[home] = None mst.addVertex(home) mst.getVertex(home).makeHome() while len(unvisited_homes) != 0: for node in visited: path, total_weight = dijsktra(g, node, unvisited_homes) curr_home = path[0] if total_weight < distTo[curr_home]: distTo[curr_home] = total_weight edgeTo[curr_home] = path v = distTo.popitem()[0] unvisited_homes.remove(v) prev = edgeTo[v].pop(0) for vertex in edgeTo[v]: if prev not in visited: visited.append(prev) weight = g.getEdgelen(prev, vertex) mst.addEdge(prev, vertex, weight) prev = vertex return mst
neighbor = {} for i in xrange(line[0]): neighbor[i] = [] for i in xrange(len(data)): data[i] = data[i].split(":") data[i][0] = data[i][0].split("-") data[i][0] = [int(data[i][0][0]) , int(data[i][0][1])] neighbor[data[i][0][0]] = neighbor[data[i][0][0]] + [data[i][0][1]] neighbor[data[i][0][1]] = neighbor[data[i][0][1]] + [data[i][0][0]] table [data[i][0][0] , data[i][0][1]] = int(data[i][1]) table [data[i][0][1] , data[i][0][0]] = int(data[i][1]) q = heapdict() q[0] = 0 for i in xrange(1, line[0]): q[i] = sys.maxint while (True): item = q.popitem() if (item[0] is line[0]-1): if (item[1] is sys.maxint): print "unreachable" else: print item[1] break;
def compress_hierarchy(graph, dendrogram, n_level_merges): graph_copy = graph.copy() n_nodes = np.shape(dendrogram)[0] + 1 compressed_dendrogram = dendrogram.copy() w = {u: 0 for u in range(n_nodes)} wtot = 0 for (u, v) in graph_copy.edges(): weight = graph_copy[u][v]['weight'] w[u] += weight w[v] += weight wtot += 2 * weight # Build the ClusterMultTree u = n_nodes cluster_trees = {t: ClusterMultTree(t, None, w[t]/float(wtot), 0., 0.) for t in range(n_nodes)} for t in range(n_nodes - 1): a = int(dendrogram[t][0]) b = int(dendrogram[t][1]) # Building of the new level left_tree = cluster_trees[a] right_tree = cluster_trees[b] pi_a = left_tree.pi pi_b = right_tree.pi w[u] = w.pop(a) + w.pop(b) pi = w[u] / float(wtot) if graph_copy.has_edge(a, b): p_ab = 2 * graph_copy[a][b]['weight'] / float(wtot) else: p_ab = 0 d_ab = pi_a * pi_b / float(p_ab) new_tree = ClusterMultTree(u, d_ab, pi, p_ab, pi_a * pi_b) new_tree.children.add(left_tree) left_tree.father = new_tree new_tree.children.add(right_tree) right_tree.father = new_tree cluster_trees[u] = new_tree # Update graph graph_copy.add_node(u) neighbors_a = list(graph_copy.neighbors(a)) neighbors_b = list(graph_copy.neighbors(b)) for v in neighbors_a: graph_copy.add_edge(u, v, weight=graph_copy[a][v]['weight']) for v in neighbors_b: if graph_copy.has_edge(u, v): graph_copy[u][v]['weight'] += graph_copy[b][v]['weight'] else: graph_copy.add_edge(u, v, weight=graph_copy[b][v]['weight']) graph_copy.remove_node(a) graph_copy.remove_node(b) u += 1 # Compute the information loss of each possible merge u = 2 * n_nodes - 2 merging_priority = heapdict() for t in list(reversed(range(n_nodes - 1))): a = int(dendrogram[t][0]) b = int(dendrogram[t][1]) left_tree = cluster_trees[a] right_tree = cluster_trees[b] current_tree = cluster_trees[u] d_ab = current_tree.d_ab p_ab = current_tree.sum_p_ab pi_a_pi_b = current_tree.sum_pi_a_pi_b # Loss computation with left level if left_tree.d_ab is not None: left_d_ab = left_tree.d_ab left_p_ab = left_tree.sum_p_ab left_pi_a_pi_b = left_tree.sum_pi_a_pi_b left_tree.up_merge_d_ab = (pi_a_pi_b + left_pi_a_pi_b) / float(p_ab + left_p_ab) left_tree.up_merge_loss = (p_ab + left_p_ab) * np.log(left_tree.up_merge_d_ab) - (p_ab * np.log(d_ab) + left_p_ab * np.log(left_d_ab)) merging_priority[left_tree.cluster_label] = left_tree.up_merge_loss # Loss computation with right level if right_tree.d_ab is not None: right_d_ab = right_tree.d_ab right_p_ab = right_tree.sum_p_ab right_pi_a_pi_b = right_tree.sum_pi_a_pi_b right_tree.up_merge_d_ab = (pi_a_pi_b + right_pi_a_pi_b) / float((p_ab + right_p_ab)) right_tree.up_merge_loss = (p_ab + right_p_ab) * np.log(right_tree.up_merge_d_ab) - (p_ab * np.log(d_ab) + right_p_ab * np.log(right_d_ab)) merging_priority[right_tree.cluster_label] = right_tree.up_merge_loss u -= 1 # Merge n_levels times for n_merges in range(n_level_merges): cluster_label, minimum_loss = merging_priority.popitem() merged_tree = cluster_trees[cluster_label] father_merged_tree = merged_tree.father # Merge the two levels # print(father_merged_tree.d_ab, merged_tree.up_merge_d_ab, merged_tree.d_ab) father_merged_tree.sum_pi_a_pi_b += merged_tree.sum_pi_a_pi_b father_merged_tree.sum_p_ab += merged_tree.sum_p_ab father_merged_tree.d_ab = merged_tree.up_merge_d_ab father_merged_tree.merged_clusters |= merged_tree.merged_clusters father_merged_tree.children |= merged_tree.children father_merged_tree.children.remove(merged_tree) for c in father_merged_tree.merged_clusters: cluster_trees[c].d_ab = father_merged_tree.d_ab # compressed_dendrogram[cluster_trees[c].cluster_label - n_nodes, 2] = father_merged_tree.d_ab # Updates the father and the children loss if father_merged_tree.father is not None: pi_a_pi_b = father_merged_tree.sum_pi_a_pi_b p_ab = father_merged_tree.sum_p_ab d_ab = father_merged_tree.d_ab father_pi_a_pi_b = father_merged_tree.father.sum_pi_a_pi_b father_p_ab = father_merged_tree.father.sum_p_ab father_d_ab = father_merged_tree.father.d_ab father_merged_tree.up_merge_d_ab = (pi_a_pi_b + father_pi_a_pi_b) / float((p_ab + father_p_ab)) father_merged_tree.up_merge_loss = (p_ab + father_p_ab) * np.log(father_merged_tree.up_merge_d_ab) - (p_ab * np.log(d_ab) + father_p_ab * np.log(father_d_ab)) merging_priority[father_merged_tree.cluster_label] = father_merged_tree.up_merge_loss for child in father_merged_tree.children: if child.d_ab is not None: pi_a_pi_b = father_merged_tree.sum_pi_a_pi_b p_ab = father_merged_tree.sum_p_ab d_ab = father_merged_tree.d_ab child_pi_a_pi_b = child.sum_pi_a_pi_b child_p_ab = child.sum_p_ab child_d_ab = child.d_ab child.up_merge_d_ab = (pi_a_pi_b + child_pi_a_pi_b) / float((p_ab + child_p_ab)) child.up_merge_loss = (p_ab + child_p_ab) * np.log(child.up_merge_d_ab) - (p_ab * np.log(d_ab) + child_p_ab * np.log(child_d_ab)) child.father = father_merged_tree merging_priority[child.cluster_label] = child.up_merge_loss label_distance = {} for cluster_label, cluster_tree in cluster_trees.items(): if cluster_tree.d_ab is not None: label_distance[cluster_label] = cluster_tree.d_ab else: label_distance[cluster_label] = 0. sorted_labels = sorted(label_distance.keys(), key=lambda label: label_distance[label]) new_labels = {old_label: new_label for new_label, old_label in enumerate(sorted_labels)} compressed_dendrogram = np.zeros(dendrogram.shape) for old_label, new_label in new_labels.items(): if old_label > n_nodes - 1: a = dendrogram[old_label - n_nodes][0] b = dendrogram[old_label - n_nodes][1] distance = cluster_trees[old_label].d_ab n = dendrogram[old_label - n_nodes][3] compressed_dendrogram[new_label - n_nodes] = [new_labels[a], new_labels[b], distance, n] return compressed_dendrogram #return reorder_dendrogram(compressed_dendrogram)
def _init_heap_with(node): to_visit = heapdict() to_visit[node] = node.unwinding_priority() return to_visit