class MedianFinder: """!有问题""" def __init__(self): """ initialize your data structure here. """ self.small = PriorityQueue() self.large = PriorityQueue() def addNum(self, num): """ :type num: int :rtype: void """ if self.large.empty() or num < self.large.queue[0]: self.large._put(num) else: self.small.put(num) if len(self.small.queue) > len(self.large.queue) + 1: self.large._put(self.small.queue.pop()) elif len(self.large.queue) > len(self.small.queue) + 1: self.small.put(self.large.queue.pop()) def findMedian(self): """ :rtype: float """ if len(self.small.queue) == len(self.large.queue): return (self.small.queue[0] + self.large.queue[0])/2 elif len(self.small.queue) < len(self.large.queue): return self.large.queue[0] else: return self.small.queue[0]
def solution(n, start, end, roads, traps): # 보드 파싱 board = [[inf] * n for _ in range(n)] for road in roads: s, e, c = road if c < board[s - 1][e - 1]: board[s - 1][e - 1] = c # return board # 모든 함정의 경우의 수 2^len(traps)에 대한 cost dict 생성 # 함정 문자열은, 모든 노드 중 밟은 함정노드가 1로 되어있는 문자열 # 이후 함정 dict를 통해 특정노드가 함정인지 아닌지 쉽게 파악가능 # 모든 함정 경우에 대해 보드도 미리 만들어 둔다 cost = {} boards = {} for i in range(len(traps) + 1): selected_traps = combinations(traps, i) for trap in selected_traps: active_traps = 0 for node in trap: active_traps += 2**(node - 1) # active_traps[node-1] = "1" cost[active_traps] = [inf] * n boards[active_traps] = swap_board(board, bin(active_traps)[2:][::-1]) cost[0][start - 1] = 0 traps = dict.fromkeys(list(map(lambda x: x - 1, traps))) # return traps # return cost # return boards # 함정상태 문자열을 가진 채로 다익스트라 고고 pq = PriorityQueue() pq._put((cost[0][start - 1], start - 1, 0)) while not pq.empty(): current_cost, current_node, current_trap_int = pq._get() if current_node == end - 1: return current_cost current_board = boards[current_trap_int] for idx, v in enumerate(current_board[current_node]): if v != inf: next_trap_int = current_trap_int if idx in traps: next_trap_int = current_trap_int ^ (1 << idx) if (cost[current_trap_int][idx] > current_cost + current_board[current_node][idx]): cost[current_trap_int][ idx] = current_cost + current_board[current_node][idx] pq._put((cost[current_trap_int][idx], idx, next_trap_int)) return min(list(map(lambda x: x[end - 1], cost.values())))
def _put(self, item): heappush = heapq.heappush if item[1] not in self.values: self.values[item[1]] = [1, 1, True] PriorityQueue._put(self, (item, 1)) else: validity = self.values[item[1]] validity[0] += 1 #Number of the valid entry validity[1] += 1 #Total number of entries if validity[2]: #Is this a replace move? self.size_diff += 1 validity[2] = True PriorityQueue._put(self, (item, validity[0]))
def _put(self, item): """ReadyQueue expects (priority, Queue<JCB>), (priority, list<JCB>) or (priority, JCB) tuples""" p, q = item if p in self._prio_levels.keys(): prio_level_queue = self._prio_levels[p] put_coll(prio_level_queue, q) else: prio_level_queue = Queue() put_coll(prio_level_queue, q) PriorityQueue._put(self, (p, prio_level_queue)) self._prio_levels[p] = prio_level_queue
def A_star_search(graph, start, goal): """ Given a graph, a start node and a goal node Utilize A* search algorithm by finding the path from start node to the goal node Use early stoping in your code This function returns back a dictionary storing the information of each node and its corresponding parent node Arguments: graph -- A dictionary storing the edge information from one node to a list of other nodes start -- A character indicating the start node goal -- A character indicating the goal node Return: came_from -- a dictionary indicating for each node as the key and value is its parent node """ came_from = {} cost_so_far = {} costso={} came_from[start] = None cost_so_far[start] = 0 costso[start]=0 ### START CODE HERE ### (≈ 15 line of code) sq=PriorityQueue() visited=[] sq._put((0,start)) while sq: parent=sq._get()[1] target = graph.edges[parent] targetcost=graph.edgeWeights[parent] if parent not in visited: visited.append(parent) if parent == goal: return came_from, cost_so_far for i in target: if (i not in cost_so_far) or (cost_so_far[i] > targetcost[target.index(i)] + cost_so_far[parent]): came_from[i]=parent cost_so_far[i]=(targetcost[target.index(i)]+cost_so_far[parent]) sq._put(((cost_so_far[i]+heuristic(graph, start, i)),i)) ### END CODE HERE ### return came_from, cost_so_far
def __init__(self,chars): q = PriorityQueue() counter = itertools.count() # unique sequence count for freq,char in chars: q._put((freq,(next(counter),HuffNode(freq=freq,val=char)))) for _ in range(len(chars)-1): left = q._get() right = q._get() freq = left[0] + right[0] z = HuffNode(freq=freq,lchild=left[1][1],rchild=right[1][1]) z.lchild.prnt = z.rchild.prnt = z q._put((freq,(next(counter),z))) self.root = q._get()[1][1] self.codes_dict = self._codes()
def UCS(self): # Fill the correct path in self.path # self.fullPath should contain the order of visited nodes self.fullPath = [] self.reset_node() pq = PriorityQueue() pq._put((0, self.startNodeIndex)) while pq.empty() == False: x = pq.get() right = self.nodes[x[1]].right left = self.nodes[x[1]].left up = self.nodes[x[1]].up down = self.nodes[x[1]].down if self.nodes[x[1]].vis == 1: continue self.fullPath.append(x[1]) if self.nodes[x[1]].value == 'E': self.totalCost = x[0] break self.nodes[x[1]].vis = 1 if up is not None and up.value != '#' and ( up.gOfN > x[0] + up.edgeCost or up.gOfN is None): up.gOfN = x[0] + self.nodes[up.id].edgeCost pq.put_nowait((self.nodes[up.id].gOfN, up.id)) up.previousNode = x[1] if down is not None and down.value != '#' and ( down.gOfN > x[0] + down.edgeCost or down.gOfN is None): down.gOfN = x[0] + down.edgeCost pq.put_nowait((self.nodes[down.id].gOfN, down.id)) down.previousNode = x[1] if left is not None and left.value != '#' and ( left.gOfN > x[0] + left.edgeCost or left.gOfN is None): left.gOfN = x[0] + left.edgeCost pq.put_nowait((left.gOfN, left.id)) left.previousNode = x[1] if right is not None and right.value != '#' and ( right.gOfN > x[0] + right.edgeCost or right.gOfN is None): right.gOfN = x[0] + self.nodes[right.id].edgeCost pq.put_nowait((self.nodes[right.id].gOfN, right.id)) right.previousNode = x[1] return self.path, self.fullPath, self.totalCost
def algorithm(draw, grid, start, end): count = 0 open_set = PriorityQueue() open_set.put((0, count, start)) came_from = {} g_score = {spot: float("inf") for row in grid for spot in row} g_score[start] = 0 f_score = {spot: float("inf") for row in grid for spot in row} f_score[start] = h(start.get_pos(), end.get_pos()) open_set_hash = {start} while not open_set.empty(): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() current = open_set.get()[2] open_set_hash.remove(current) if current == end: reconstruct_path(came_from, end, draw) end.make_end() return True for neighbor in current.neighbors: temp_g_score = g_score[current] + 1 if temp_g_score < g_score[neighbor]: came_from[neighbor] = current g_score[neighbor] = temp_g_score f_score[neighbor] = temp_g_score + h(neighbor.get_pos(), end.get_pos()) if neighbor is not open_set_hash: count += 1 open_set._put((f_score[neighbor], count, neighbor)) open_set_hash.add(neighbor) neighbor.make_open() draw() if current != start: current.make_closed() return False
class Dijkstra: def __init__(self,gameboard): self.grid = [[None for x in range(gameboard.height)] for x in range(gameboard.width)] self.run() self.qset = queue() self.pqueue = PriorityQueue() def run(self, gameboard,x,y): print(gameboard.height*gameboard.width) for i in range (gameboard.height): for j in range (gameboard.width): self.grid[i][j] = grid(i,j,999) self.pqueue._put(self.grid[i][j]) self.grid[x][y]=0 while self.pqueue.empty(): lilgrid = self.pqueue._get() pass
def solution(n, start, end, roads, traps): # 보드 파싱 board = [[inf] * n for _ in range(n)] for road in roads: s, e, c = road if c < board[s - 1][e - 1]: board[s - 1][e - 1] = c # return board # 모든 함정의 경우의 수 2^len(traps)에 대한 cost dict 생성 # 함정 문자열은, 모든 노드 중 밟은 함정노드가 1로 되어있는 문자열 # 이후 함정 dict를 통해 특정노드가 함정인지 아닌지 쉽게 파악가능 # 모든 함정 경우에 대해 보드도 미리 만들어 둔다 cost = {} for i in range(len(traps) + 1): selected_traps = combinations(traps, i) for trap in selected_traps: active_traps = 0 for node in trap: active_traps += 2**(node - 1) # active_traps[node-1] = "1" cost[active_traps] = [inf] * n cost[0][start - 1] = 0 traps = dict.fromkeys(list(map(lambda x: x - 1, traps))) # return traps # return cost # 함정상태 문자열을 가진 채로 다익스트라 고고 pq = PriorityQueue() pq._put((cost[0][start - 1], start - 1, 0)) while not pq.empty(): current_cost, current_node, current_trap_int = pq._get() current_trap_str = bin(current_trap_int)[2:].zfill(n)[::-1] if current_node == end - 1: return current_cost from_there = [_[current_node] for _ in board] to_here = board[current_node] next_nodes = [ i for i, x in enumerate(zip(from_there, to_here)) if x[0] != inf or x[1] != inf ] for idx in next_nodes: if idx in traps: next_trap_int = current_trap_int ^ (1 << idx) else: next_trap_int = current_trap_int if ((current_trap_str[current_node] == "1" and current_trap_str[idx] == "1") or (current_trap_str[current_node] == "0" and current_trap_str[idx] == "0")): current_edge = board[current_node][idx] else: current_edge = board[idx][current_node] if current_edge != inf: if (cost[current_trap_int][idx] > current_cost + current_edge): cost[current_trap_int][idx] = current_cost + current_edge pq._put((cost[current_trap_int][idx], idx, next_trap_int)) return min(list(map(lambda x: x[end - 1], cost.values())))
def _put(self, item): if item[1] not in self.values: self.values.add(item[1]) PriorityQueue._put(self, item) else: pass
def uniform_cost_search(graph, start, goal): """ Given a graph, a start node and a goal node Utilize uniform cost search algorithm by finding the path from start node to the goal node Use early stoping in your code This function returns back a dictionary storing the information of each node and its corresponding parent node Arguments: graph -- A dictionary storing the edge information from one node to a list of other nodes start -- A character indicating the start node goal -- A character indicating the goal node Return: came_from -- a dictionary indicating for each node as the key and value is its parent node """ came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 ### START CODE HERE ### (≈ 15 line of code) if start not in graph.edges: print(" the ", start, "not exist in", graph) return {}, {} elif goal not in graph.edges: print(" the ", goal, "not exist in", graph) return {}, {} else: sq = PriorityQueue() visited = [] sq._put((0, start)) while sq: parent = sq._get()[1] target = graph.edges[parent] targetcost = graph.edgeWeights[parent] if parent not in visited: visited.append(parent) if parent == goal: return came_from, cost_so_far for i in target: if (i not in cost_so_far) or ( cost_so_far[i] > targetcost[target.index(i)] + cost_so_far[parent]): came_from[i] = parent print(came_from) cost_so_far[i] = (targetcost[target.index(i)] + cost_so_far[parent]) sq._put((cost_so_far[i], i)) print(sq.queue) # target = graph.edges[start] # targetcost=graph.edgeWeights[start] # parent = start # while goal not in target: # for item in target: # if (item not in cost_so_far) or (cost_so_far[item]>targetcost[target.index(item)]+cost_so_far[parent]): # came_from[item] = parent # cost_so_far[item]=targetcost[target.index(item)]+cost_so_far[parent] # sq._put((cost_so_far[item], item)) # parent= sq._get()[1] # targetcost=graph.edgeWeights[parent] # target = graph.edges[parent] # came_from[goal] = parent # cost_so_far[goal]=targetcost[target.index(goal)]+cost_so_far[parent] ### END CODE HERE ### return came_from, cost_so_far
from dataclasses import dataclass, field from queue import PriorityQueue @dataclass(order=True) class Person: name: str = field(compare=False) priority: int = 0 greater_than: set = field(default_factory=set, compare=False) def main(): n, m = map(int, input().split()) names = input().split() people = {name: Person(name) for name in names} a = PriorityQueue() a._put(Person("jon", 0)) a._put(Person("jona", 2)) a._put(Person("helgi", 6)) a._put(Person("bardur", 3)) print(a._get().name) print(a._get().name) print(a._get().name) print(a._get().name)
def solution(n, start, end, roads, traps): # 보드 생성 # 역간선을 미리 만들어 둔다 board = {} for road in roads: s, e, c = road if not s - 1 in board: board[s - 1] = {} if not e - 1 in board: board[e - 1] = {} board[s - 1][e - 1] = [c, 1] board[e - 1][s - 1] = [c, -1] # return board # 함정 상태별 최소거리 cost 기록 # 보드도 미리 만들어 둔다 cost = {} boards = {} for i in range(len(traps) + 1): selected_traps = combinations(traps, i) for trap in selected_traps: active_traps = 0 for node in trap: active_traps += 2**(node - 1) # active_traps[node-1] = "1" cost[active_traps] = [inf] * n boards[active_traps] = swap_board(board, bin(active_traps)[2:][::-1]) # return boards cost[0][start - 1] = 0 traps = dict.fromkeys(list(map(lambda x: x - 1, traps))) # return traps # 함정상태 문자열을 가진 채로 다익스트라 고고 pq = PriorityQueue() pq._put((cost[0][start - 1], start - 1, 0)) while not pq.empty(): current_cost, current_node, current_trap_int = pq._get() if current_node == end - 1: return current_cost current_board = boards[current_trap_int] for k, v in current_board[current_node].items(): if v[1] == 1: next_trap_int = current_trap_int if k in traps: next_trap_int = current_trap_int ^ (1 << k) if (cost[current_trap_int][k] > current_cost + current_board[current_node][k][0]): cost[current_trap_int][ k] = current_cost + current_board[current_node][k][0] pq._put((cost[current_trap_int][k], k, next_trap_int)) return min(list(map(lambda x: x[end - 1], cost.values())))
def _put(self, prioritized_item, heappush=heapq.heappush): priority = prioritized_item[0] data = prioritized_item[1] item = (priority, self._counter, data) self._counter += 1 PriorityQueue._put(self, item)
def _put(self, item): # Called by the put method after aquiring locks etc... if item[1] not in self.values: PriorityQueue._put(self, item) self.values.add(item[1])