public ListNode mergeKLists(ArrayList<ListNode> lists) { if (lists.size() == 0) return null; PriorityQueue<ListNode> q = new PriorityQueue<ListNode>( lists.size(), new Comparator<ListNode>() { public int compare(ListNode a, ListNode b) { if (a.val > b.val) return 1; else if (a.val == b.val) return 0; else return -1; } }); for (ListNode i : lists) if (i != null) q.add(i); ListNode head = new ListNode(-1); ListNode pre = head; while (q.size() != 0) { ListNode temp = q.poll(); pre.next = temp; if (temp.next != null) q.add(temp.next); pre = pre.next; } return head.next; }
public static ListNode mergeKlists(List<ListNode> lists) { if (lists.size() == 0) return null; PriorityQueue<ListNode> p = new PriorityQueue<ListNode>( lists.size(), new Comparator<ListNode>() { @Override public int compare(ListNode a, ListNode b) { return a.val - b.val; } }); for (ListNode list : lists) { if (list != null) p.add(list); } ListNode head = new ListNode(0); ListNode result = head; while (p.size() > 0) { ListNode temp = p.poll(); result.next = temp; if (temp.next != null) { p.add(temp.next); } result = result.next; } return head.next; }
public static void main(String[] args) { Scanner in = new Scanner(System.in); PriorityQueue<Node> pq = new PriorityQueue<Node>(); HashSet<Integer> visited = new HashSet<Integer>(); int n = in.nextInt(); int[][] am = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { am[i][j] = in.nextInt(); if (i == j) am[i][j] = Integer.MAX_VALUE; } n = in.nextInt(); int a, b; while (n-- > 0) { a = in.nextInt() - 1; b = in.nextInt() - 1; am[a][b] = 0; am[b][a] = 0; } int ret = 0; pq.add(new Node(0, 0)); Node curr; while (!pq.isEmpty()) { curr = pq.poll(); if (visited.contains(curr.a)) continue; ret += curr.w; visited.add(curr.a); for (int i = 0; i < am.length; i++) { pq.add(new Node(i, am[curr.a][i])); } } System.out.println(ret); }
public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>( lists.length, new Comparator<ListNode>() { @Override public int compare(ListNode a, ListNode b) { if (a.val > b.val) return 1; else if (a.val == b.val) return 0; else return -1; } }); for (ListNode list : lists) { if (list != null) queue.add(list); } ListNode head = new ListNode(0); ListNode p = head; while (queue.size() > 0) { ListNode tmp = queue.poll(); p.next = tmp; // keep adding next node in list if (tmp.next != null) queue.add(tmp.next); p = p.next; } return head.next; }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue. * * @return the head of this queue * @throws InterruptedException {@inheritDoc} */ public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) available.await(); else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay <= 0) return q.poll(); else if (leader != null) available.await(); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { available.awaitNanos(delay); } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
public static void testPQ(int count) { PriorityQueue pq = new IntegerQueue(count); Random gen = new Random(); int sum = 0, sum2 = 0; for (int i = 0; i < count; i++) { int next = gen.nextInt(); sum += next; pq.put(new Integer(next)); } // Date end = new Date(); // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000); // System.out.println(" microseconds/put"); // start = new Date(); int last = Integer.MIN_VALUE; for (int i = 0; i < count; i++) { Integer next = (Integer) pq.pop(); assertTrue(next.intValue() >= last); last = next.intValue(); sum2 += last; } assertEquals(sum, sum2); // end = new Date(); // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000); // System.out.println(" microseconds/pop"); }
public void add(int x) { if (min.size() <= max.size()) { min.add(x); } else { max.add(x); } }
// Busqueda usando A* public static int search() { HashSet<State> v = new HashSet<>(); Giros mano = new Giros(); ArrayList<int[][]>aux; finall = inicial.createGoalState(); Q.add(inicial); Node actual; int cont = 0; while ( !(actual = Q.remove()).estado.equals(finall.estado) ) { if(v.contains(actual.estado)) continue; System.out.println(actual.estado+" "+actual.costo_hasta_aqui+" "+actual.costo_total); System.out.println("->\n"+((NodeCubo)actual).getValue() ); v.add(actual.estado); int ca = actual.costo_hasta_aqui + 1; //Realiza Movimientos for( int i=0; i<12; i++ ){ aux = mano.girar( ((Cubo)actual.getValue()).getCubo(), i); Node nuevo = new NodeCubo(ca, ca+Heuristica.h1((Cubo)actual.getValue()), new Cubo( aux, ((Cubo)inicial.getValue()).getColors() ) ); Q.add( (Node)nuevo ); } cont++; } return cont; }
/** * @param k: The number k. * @return: The kth prime number as description. */ public long kthPrimeNumber(int k) { PriorityQueue<Long> queue = new PriorityQueue<Long>(); HashMap<Long, Boolean> map = new HashMap<Long, Boolean>(); Long[] Primes = new Long[3]; Primes[0] = Long.valueOf(3); Primes[1] = Long.valueOf(5); Primes[2] = Long.valueOf(7); for (int i = 0; i < Primes.length; ++i) { queue.add(Primes[i]); map.put(Primes[i], true); } Long number = Primes[0]; for (int i = 1; i <= k; ++i) { number = queue.poll(); for (int j = 0; j < Primes.length; ++j) { if (map.containsKey(number * Primes[j])) { continue; } else { map.put(number * Primes[j], true); queue.add(number * Primes[j]); } } } return number; }
private static PencilPosition findShortestRoute(int[][] maze) { // all found solutions to the maze PriorityQueue<PencilPosition> solutions = new PriorityQueue<PencilPosition>(5, new PencilPositionComparator()); // bread-first search queue Queue<PencilPosition> routes = new LinkedList<PencilPosition>(); // set of already visited positions Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>(); // add the starting positions, which is always (0,0) routes.add(new PencilPosition(0, 0, false, null)); while (!routes.isEmpty()) { PencilPosition position = routes.poll(); // if this is the destinations position then we've found a solution if (0 == maze[position.row][position.column]) { solutions.add(position); continue; } // if we haven't already visited this position if (!visitedPositions.contains(position)) { routes.addAll(findPossibleRoutes(position, maze)); visitedPositions.add(position); } } return solutions.poll(); }
private void assertMinimumsAreEqual( java.util.PriorityQueue<Integer> oldQueue, PriorityQueue<Integer> newQueue) { assertThat(oldQueue.isEmpty()).isEqualTo(newQueue.isEmpty()); if (!newQueue.isEmpty()) { assertThat(oldQueue.peek()).isEqualTo(newQueue.head()); } }
public List<Task> mockRunTaks(List<Task> tasks) { PriorityQueue<Task> taskQueue = new PriorityQueue<Task>( new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { return t1.priority - t2.priority; } }); List<Task> runOrder = new ArrayList<Task>(); HashMap<Task, Integer> taskIndegrees = new HashMap<Task, Integer>(); for (Task task : tasks) { taskIndegrees.put(task, task.dependencies.size()); if (task.dependencies.size() == 0) { taskQueue.offer(task); } } while (!taskQueue.isEmpty()) { Task curTask = taskQueue.poll(); runOrder.add(curTask); for (Task task : curTask.dependencies) { taskIndegrees.put(task, taskIndegrees.get(task) - 1); if (taskIndegrees.get(task) == 0) taskQueue.offer(task); } } return runOrder; }
// Adds a number into the data structure. public void addNum(int num) { minHeap.offer(num); if (minHeap.size() - maxHeap.size() > 1) { maxHeap.offer(minHeap.poll()); } }
@Override public E next() { h = (E) temp.head(); temp = temp.tail(); return h; }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue, or the specified wait time expires. * * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before * an element with an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay > 0) { if (nanos <= 0) return null; if (delay > nanos) delay = nanos; long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } else { E x = q.poll(); assert x != null; if (q.size() != 0) available.signalAll(); return x; } } } } finally { lock.unlock(); } }
public ListNode mergeKLists(List<ListNode> lists) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(1024); List<ListNode> ps = new ArrayList<>(); ListNode root = new ListNode(0); ListNode cur = root; boolean nothingNew = false; for (ListNode list : lists) ps.add(list); while (true) { nothingNew = true; for (int i = 0; i < ps.size(); i++) { ListNode list = ps.get(i); if (list != null) { nothingNew = false; pq.offer(list.val); ps.set(i, list.next); } } if (nothingNew) break; cur.next = new ListNode(pq.poll()); cur = cur.next; } while (pq.size() > 0) { cur.next = new ListNode(pq.poll()); cur = cur.next; } return root.next; }
/** * Retrieves and removes the head of this queue, waiting if necessary until an element with an * expired delay is available on this queue, or the specified wait time expires. * * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before * an element with an expired delay becomes available * @throws InterruptedException {@inheritDoc} */ public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { for (; ; ) { E first = q.peek(); if (first == null) { if (nanos <= 0) return null; else nanos = available.awaitNanos(nanos); } else { long delay = first.getDelay(TimeUnit.NANOSECONDS); if (delay <= 0) return q.poll(); if (nanos <= 0) return null; if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos); else { Thread thisThread = Thread.currentThread(); leader = thisThread; try { long timeLeft = available.awaitNanos(delay); nanos -= delay - timeLeft; } finally { if (leader == thisThread) leader = null; } } } } } finally { if (leader == null && q.peek() != null) available.signal(); lock.unlock(); } }
public void MEC2(Process process) throws IOException { process.setState("Running"); int clock = 0; // while loop to execute instructions while (true) { clock++; if (isTermenated()) { // if the process terminates, then break the method process.setState("Terminated"); if (!IOBoundJob.isExist(process)) CPUBoundJob.enqueue(process, 0); Statistic.NUMBER_OF_EXECUTED_PROCESSES++; file.writeProcess(process); RAM.loadProcessFromHardDisk(); return; } if (isInterrupted(process)) { // if the process interrupted, then return the process to the Ready Queue (RAM) process.setState("Ready"); process.setRemainingTime(process.getRemainingTime() - clock); RAM.returnProcess(process); return; } } }
/** * piirtää reitin tiedostoon ja reittikartta taulukkoon * * @param käydytsolmut * @throws IOException */ public void piirräreitti(PriorityQueue<Solmu> käydytsolmut) throws IOException { String nimi = new String("uk"); BufferedWriter reittikarttatiedosto = new BufferedWriter(new FileWriter("uk")); Solmu solmu = new Solmu(0, 0, null, 0); while (!käydytsolmut.isEmpty()) { solmu = käydytsolmut.poll(); for (int n = 0; n < kartankoko; n++) { for (int i = 0; i < kartankoko; i++) { if (solmu.x == n && solmu.y == i) { // reittikartta[i][n] = '-'; reittikartta[i][n] = (char) (solmu.summaamatkat(0, solmu.annavanhempi()) + 65); // reittikarttatiedosto.write("-"); reittikarttatiedosto.write('-'); } else { reittikarttatiedosto.write(reittikartta[i][n]); } } reittikarttatiedosto.newLine(); } } reittikarttatiedosto.close(); tulostakartta(reittikartta); }
@Test public void shouldNarrowQueue() { final PriorityQueue<Double> doubles = of(1.0d); final PriorityQueue<Number> numbers = PriorityQueue.narrow(doubles); final int actual = numbers.enqueue(new BigDecimal("2.0")).sum().intValue(); assertThat(actual).isEqualTo(3); }
/* * Initialise Method * @params start and goal coordinates */ public void init(int sX, int sY, int gX, int gY) { cellHash.clear(); path.clear(); openHash.clear(); while (!openList.isEmpty()) openList.poll(); k_m = 0; s_start.x = sX; s_start.y = sY; s_goal.x = gX; s_goal.y = gY; CellInfo tmp = new CellInfo(); tmp.g = 0; tmp.rhs = 0; tmp.cost = C1; cellHash.put(s_goal, tmp); tmp = new CellInfo(); tmp.g = tmp.rhs = heuristic(s_start, s_goal); tmp.cost = C1; cellHash.put(s_start, tmp); s_start = calculateKey(s_start); s_last = s_start; }
public static <E> List<E> sortedKeys(Counter<E> counter) { List<E> sortedKeyList = new ArrayList<E>(); PriorityQueue<E> pq = counter.asPriorityQueue(); while (pq.hasNext()) { sortedKeyList.add(pq.next()); } return sortedKeyList; }
public static void solveOne() throws Exception { int n = nextInt(); int m = nextInt(); int k = nextInt(); int w = nextInt(); char[][][] levels = new char[k][n][]; ; for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { levels[i][j] = nextString().toCharArray(); } } int[][] cost = new int[k][k]; PriorityQueue<int[]> q = new PriorityQueue<>( k * k, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[2] - o2[2]; } }); for (int i = 0; i < k; i++) { for (int j = i + 1; j < k; j++) { int[] cur = {i, j, diff(levels[i], levels[j]) * w}; cost[i][j] = cur[2]; q.add(cur); // px("edge", cur); } } // px(q.size()); // for (int[] e: cost) px(e); DisjointUnionSet djs = new DisjointUnionSet(k); boolean[][] al = new boolean[k][k]; int finalCost = n * m * k; for (; q.size() > 0; ) { int[] edge = q.poll(); int p1 = djs.getPartitionId(edge[0]); int p2 = djs.getPartitionId(edge[1]); // px(edge, p1 == p2, edge[2]); if (edge[2] > n * m) break; if (p1 != p2) { djs.unionElement(edge[0], edge[1]); finalCost -= n * m - edge[2]; al[edge[1]][edge[0]] = true; al[edge[0]][edge[1]] = true; } } // for (boolean[] e: al) px(e); pn(finalCost); boolean[] ex = new boolean[k]; for (int i = 0; i < k; i++) { if (!ex[i]) { dfs(i, -1, ex, k, al); } } }
public static void dijkstra_function(graph G, int s, int no) throws IOException { // s is the index of the starting vertex // declare variables int nVerts, u, v; int[] dist; nVerts = G.vertices(); // get number of vertices in the graph class // initialize array dist = new int[nVerts]; Stack[] path = new Stack[nVerts]; for (v = 0; v < nVerts; v++) // initializations { dist[v] = 99999; // 99999 represents infinity path[v] = new Stack<Integer>(); path[v].push(s); } // end for dist[s] = 0; PriorityQueue Q = new PriorityQueue(dist); while (Q.Empty() == 0) // if heap is not empty { u = Q.Delete_root(); v = G.nextneighbor(u); while (v != -1) // for each neighbor of u { if (dist[v] > dist[u] + G.edgeLength(u, v)) { dist[v] = dist[u] + G.edgeLength(u, v); path[v].pop(); path[v].push(u); Q.Update(v, dist[v]); } v = G.nextneighbor(u); // get the next neighbor of u } // end while } // end while for (v = 0; v < nVerts; v++) // initializations { while ((Integer) path[v].peek() != s) { int top = (Integer) path[v].peek(); for (int i = 0; i < path[top].size(); i++) { path[v].push(path[top].get(i)); } } } FileWriter fw = new FileWriter("path" + no + ".txt"); for (int i = 0; i < nVerts; i++) { fw.write(dist[i] + " "); while (!path[i].empty()) fw.write((Integer) path[i].pop() + " "); fw.write(i + "\n"); } // end for fw.close(); } // end bfs_function
public Job getJob(int id) { Job retJob = null; retJob = Am.getJob(id); if (retJob == null) { retJob = A1in.getJob(id); } return retJob; }
@Test public void shouldMergeTwoPriorityQueues() { final PriorityQueue<Integer> source = of(3, 1, 4, 1, 5); final PriorityQueue<Integer> target = of(9, 2, 6, 5, 3); assertThat(source.merge(target)).isEqualTo(of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3)); assertThat(PriorityQueue.of(3).merge(PriorityQueue.of(toStringComparator(), 1))) .isEqualTo(of(3, 1)); }
/** * initial for routing, if the start node is an intersect, then it should already in the adjlist, * than we just add it. If the start node is not intersect, then the node will not in adjlist, we * need find the node's two edge entrance if the edge is bidirection or one edge entrance if the * edge is oneway. * * @param startNode * @param endNode * @param startTime * @param dayIndex * @param nodeHelperCache */ public static PriorityQueue<NodeInfoHelper> initialStartSet( long startNode, long endNode, int startTime, int dayIndex, HashMap<Long, NodeInfoHelper> nodeHelperCache) { PriorityQueue<NodeInfoHelper> openSet = new PriorityQueue<NodeInfoHelper>( 10000, new Comparator<NodeInfoHelper>() { public int compare(NodeInfoHelper n1, NodeInfoHelper n2) { return (int) (n1.getTotalCost() - n2.getTotalCost()); } }); NodeInfo start = OSMData.nodeHashMap.get(startNode); NodeInfoHelper current; // initial start end set if (start.isIntersect()) { // initial current = new NodeInfoHelper(startNode); current.setCost(0); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(startNode, endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } else { EdgeInfo edge = start.getOnEdgeList().getFirst(); double travelTime = 1; // second int distance; // feet int totalDistance = edge.getDistance(); // feet if (!edge.isOneway()) { // distance from start to middle distance = edge.getStartDistance(startNode); travelTime = edge.getTravelTime(startTime, dayIndex, false); travelTime *= (double) distance / totalDistance; travelTime /= OSMParam.MILLI_PER_SECOND; current = new NodeInfoHelper(edge.getStartNode()); current.setCost(travelTime); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(edge.getStartNode(), endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } // distance from middle to end distance = edge.getEndDistance(startNode); travelTime = edge.getTravelTime(startTime, dayIndex, true); travelTime *= (double) distance / totalDistance; current = new NodeInfoHelper(edge.getEndNode()); current.setCost(travelTime); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(edge.getEndNode(), endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } return openSet; }
public void printCurrentList() { PriorityQueue<Node> pq = new PriorityQueue<Node>(nodes); AStarNode p; System.out.print("\n["); while ((p = (AStarNode) pq.poll()) != null) { System.out.print("\n"); p.printNode(); } System.out.println("]"); }
public static String next() { if (pq.peek() != null) { System.out.println("queue pop"); String curUrl = pq.remove().url; if (!visitedUrl.contains(curUrl)) { visitedUrl.add(curUrl); return curUrl; } else return null; } else return null; }
public int findKthLargest(int[] nums, int k) { // o(n*log(k+1)) PriorityQueue<Integer> largeK = new PriorityQueue<Integer>(k + 1); // min heap for (int e : nums) { largeK.add(e); if (largeK.size() > k) { largeK.poll(); // remove the least of k+1 } } return largeK.poll(); // return the least of k }