static void test00() { Aron.beg(); PriorityQueue<Interval> queue = new PriorityQueue<Interval>(); Stack<Interval> stack = new Stack<Interval>(); int[] arr1 = {4, 1, 2, 6, 9}; int[] arr2 = {5, 1, 4, 9, 10}; for (int i = 0; i < arr1.length; i++) { queue.add(new Interval(arr1[i], arr2[i])); } if (queue.size() > 0) { stack.push(queue.remove()); } while (!queue.isEmpty()) { Interval top = stack.peek(); Interval inter = queue.remove(); if (top.end < inter.begin) stack.push(inter); else { stack.peek().end = Math.max(stack.peek().end, inter.end); } } while (!stack.empty()) { System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]"); stack.pop(); } Aron.end(); }
public void reduce( Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { while (values.hasNext()) { String line = values.next().toString(); String[] tokens = line.split(","); try { double latitude = (Double.parseDouble(tokens[2])); double longitude = (Double.parseDouble(tokens[3])); Tuple t = new Tuple(longitude, latitude, line); t.setDistance(fp); if (queue.size() < k) { queue.add(t); } else { if (t.distance < queue.peek().distance) { queue.add(t); queue.remove(); } } } catch (Exception c) { } } while (!queue.isEmpty()) { output.collect(new Text("1"), new Text(queue.remove().tupleData)); } }
public void run() { synchronized (this) { ConnectionState connState; while (!Thread.interrupted()) { try { while (mRetryQueue.isEmpty()) wait(); connState = mRetryQueue.peek(); if (!connState.connected) { synchronized (connState) { long diffTime = connState.nextRetry - System.currentTimeMillis(); if (diffTime <= 0) { mRetryQueue.remove(connState); /** * if (!mQuietMode) log.info("Attempting to re-establish " "connection to " + * connState.serviceName + " at " + connState.addr); */ SendConnectRequest(connState); } else { wait(diffTime); } } } else mRetryQueue.remove(connState); } catch (InterruptedException e) { e.printStackTrace(); } } } }
// O(V) + O(V * V + E) = O(V^2 + E) = O(V^2) if queue is un-ordered linked list // O(V * logV) + O(V * logV + E * logV) = O((V + E)logV) public static final void dijkstra(DijkVertex[] vertices, DijkVertex src) { // Initialize vertices prev and cost (intrinsically done already except for source) src.cost = 0; // Setup priority queue maintaining min cost vertices at the start of queue PriorityQueue<DijkVertex> q = new PriorityQueue<DijkVertex>(vertices.length, new DijkVertexComparator()); q.addAll(Arrays.asList(vertices)); // Go through queue removing min vertex each iteration while (!q.isEmpty()) { DijkVertex v = q.remove(); // If cost of next node is MAX, it is not connected to source // Due to priority queue, all nodes after next node are also not connected to source // so can just return if (v.cost == Integer.MAX_VALUE) { return; } // For each edge leaving vertex, relax for (int i = 0; i < v.edges.length; i++) { if (v.cost + v.edges[i].cost < v.edges[i].dst.cost) { v.edges[i].dst.cost = v.cost + v.edges[i].cost; v.edges[i].dst.prev = v; // Remove and add updated vertex to queue to place it in correct location // after being updated q.remove(v.edges[i].dst); q.add(v.edges[i].dst); } } } }
public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { N = Integer.parseInt(br.readLine()); P = new int[N][N]; RP = new boolean[N][N]; D = new double[N]; nodes = new HNode[N]; Fix = new boolean[N]; String[] chunks; for (int i = 0; i < N; i++) { chunks = br.readLine().split(" "); for (int j = 0; j < N; j++) { P[i][j] = Integer.parseInt(chunks[j]); if (P[i][j] > 0 && i != j) RP[j][i] = true; } } if (N == 1) { System.out.println(0); return; } for (int i = 0; i < N - 1; i++) { if (RP[N - 1][i]) { D[i] = (double) 100 / (double) P[i][N - 1]; nodes[i] = new HNode(D[i], i, 1, (1.0 - (double) P[i][N - 1] / (double) 100)); heap.add(nodes[i]); } else { D[i] = Double.MAX_VALUE; nodes[i] = new HNode(D[i], i, 1, 1); } } HNode minHeap; while (!heap.isEmpty()) { minHeap = heap.remove(); if (minHeap.id == 0) { System.out.println(minHeap.dis); break; } Fix[minHeap.id] = true; for (int j = 0; j < N - 1; j++) { if (RP[minHeap.id][j] && !Fix[j]) { // j is the parent of min heap double p = (double) P[j][minHeap.id] / (double) 100; nodes[j].a = nodes[j].a + nodes[j].b * p * minHeap.dis; nodes[j].b = nodes[j].b * (1 - p); double newDis = nodes[j].a / (1 - nodes[j].b); heap.remove(nodes[j]); nodes[j].dis = newDis; heap.add(nodes[j]); } } } } catch (IOException ioe) { ioe.printStackTrace(); } }
@SuppressWarnings("unchecked") @Override public boolean remove(Object arg0) { try { return queue.remove(arg0) && decrement(((Wrapped) arg0).getWrapped()); } catch (ClassCastException e) { } try { T arg = (T) arg0; return queue.remove(new Wrapped(arg)) && decrement(arg); } catch (ClassCastException e) { } return false; }
private int getMyTarget(int[] shotAt) { /*PriorityTuple firstTuple=priorityList.remove(); if(shotAt[firstTuple.getPlayerId()]>0) return firstTuple.getPlayerId(); PriorityTuple nextTuple; if(priorityList.size()!=0) nextTuple=priorityList.remove(); while(nextTuple.getPriority()==firstTuple.getPriority()) { if(shotAt[firstTuple.getPlayerId()]<shotAt[nextTuple.getPlayerId()]) return nextTuple.getPlayerId(); if(priorityList.size()!=0) nextTuple=priorityList.remove(); else break; } return firstTuple.getPlayerId();*/ return priorityList.remove().getPlayerId(); }
@Override public T remove() { pruneToDuration(); T item = queue.remove().getWrapped(); decrement(item); return item; }
private boolean add(TimeWrapped arg0) { pruneToDuration(); if (arg0.getWrapped() == null) return false; if (queue.size() >= capacity) { try { ((CapacityOverflowHandler<T>) continuation) .handleCapacityOverflow(queue.remove().getWrapped()); } catch (NullPointerException e) { queue.remove(); } catch (ClassCastException e) { queue.remove(); } } increment(arg0.getWrapped()); return queue.add(arg0); }
/** * moves / increments turn based off of players priority queue * * @throws IOException exception */ private static void movePhaseTurnIncre() throws IOException { if (playerOrder.isEmpty()) { for (Player p : Configurations.getPlayers()) { playerOrder.add(p); } Configurations.setRound(Configurations.getRound() + 1); if (Configurations.getPhase() == 1) { produce(); } } Configurations.setCurPlayer(playerOrder.remove()); if (Configurations.getPhase() != 0) { if (Math.random() < .27) { Configurations.getCurPlayer().setMessage(applyRandomEvent()); Configurations.getGameScreenController() .updateText(Configurations.getCurPlayer().getMessage()); } else { Configurations.getCurPlayer().setMessage(""); Configurations.getGameScreenController() .updateText(Configurations.getCurPlayer().getMessage()); } } else { Configurations.getGameScreenController().updateText(); } }
private void Loop() { while (!H.isEmpty()) { Cell v = H.poll(); if (Log.ON) Log.write("popped: " + potentialField[v.col][v.row]); frozenDjogurt[v.col][v.row] = true; for (Cell vn : map.doSomeMagic(v)) { if (Log.ON) { Log.write("\n" + toString(v)); Log.write("\n" + printStack()); } if (!(map.cells[vn.col][vn.row].type == CellType.OBSTACLE)) { if (!frozenDjogurt[vn.col][vn.row]) { double d = computeArrivalTime(vn); if (d > maxElement) maxElement = d; if (!H.contains(vn)) { potentialField[vn.col][vn.row] = d; H.add(vn); } else { // if(potentialField[vn.col][vn.row] > d) // { H.remove(vn); potentialField[vn.col][vn.row] = d; H.add(vn); // } } } } } } }
public static void main(String[] args) throws IOException { int n = readInt(); int[] dogs = new int[n]; ArrayList<ArrayList<Integer>> adjlist = new ArrayList<ArrayList<Integer>>(); for (int x = 0; x < n; x++) { dogs[x] = readInt(); adjlist.add(new ArrayList<Integer>()); } int m = readInt(); for (int x = 0; x < m; x++) { int a = readInt() - 1; int b = readInt() - 1; adjlist.get(a).add(b); } int time = readInt(); int[] bark = new int[n]; PriorityQueue<Dog> moves = new PriorityQueue<Dog>(); moves.add(new Dog(0, 0)); bark[0] = 0; int[] total = new int[n]; while (!moves.isEmpty()) { Dog curr = moves.poll(); if (curr.time > time) continue; bark[curr.id] = 0; total[curr.id]++; for (int x = 0; x < adjlist.get(curr.id).size(); x++) { int next = adjlist.get(curr.id).get(x); if ((bark[next] != 0 && curr.time + dogs[next] > bark[next])) continue; moves.remove(new Dog(next, curr.time + dogs[next])); bark[next] = curr.time + dogs[next]; moves.offer(new Dog(next, curr.time + dogs[next])); } } for (int x : total) System.out.println(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; }
public static List<Star> findClosestKStars(int k, ObjectInputStream osin) { // maxHeap to store the closest k stars seen so far. PriorityQueue<Star> maxHeap = new PriorityQueue<>(k, Collections.reverseOrder()); try { while (true) { // Add each star to the max-heap. If the max-heap size exceeds k, // remove the maximum element from the max-heap. Star star = (Star) osin.readObject(); maxHeap.add(star); if (maxHeap.size() == k + 1) { maxHeap.remove(); } } } catch (IOException e) { // Do nothing, read last element in stream. } catch (ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e.getMessage()); } // We cannot go directly to an ArrayList from PriorityQueue, since // unlike LinkedList, it does not guarantee ordering of entries. List<Star> orderedStars = new ArrayList<Star>(maxHeap); // We need to reverse the orderedStars list since it goes from // largest to smallest because the PriorityQueue used the // Collections.reverse() comparator. Collections.reverse(orderedStars); return orderedStars; }
/** Implementation of dijkstra's algorithm using a binary heap. */ private void dijkstra(final PriorityQueue<Vertex> q) { Vertex u, v; while (!q.isEmpty()) { u = q.poll(); // vertex with shortest distance (first iteration // will return source) // System.out.println("id is"+u.getId()); // System.out.println(u.getDist()); // System.out.println(u.getNeighborV().size()); // System.out.println(this.endNodeId) if (u.getDist() == Double.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) // since they are unreachable // look at distances to each neighbor for (Map.Entry<Vertex, Double> a : u.getNeighborV().entrySet()) { v = a.getKey(); // the neighbor in this iteration double alternateDist = u.getDist() + a.getValue(); if (alternateDist < v.getDist()) { // shorter path to neighbor // found // System.out.println("+++++"); q.remove(v); v.setDist(alternateDist); // System.out.println(v.getId()); // System.out.println(v.getDist()); v.setPrevious(u); q.add(v); // System.out.println(q.size()); } } } }
public int[] maxSlidingWindow(int[] nums, int k) { if (nums.length == 0 || k == 0) { return new int[] {}; } int[] result = new int[nums.length - k + 1]; PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>( k, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (o1 < o2) { return 1; } else if (o1 > o2) { return -1; } else { return 0; } } }); Deque<Integer> deque = new LinkedList<Integer>(); for (int i = 0; i < k; i++) { deque.addLast(nums[i]); priorityQueue.add(nums[i]); } for (int i = k; i < nums.length; i++) { result[i - k] = priorityQueue.peek(); int first = deque.removeFirst(); priorityQueue.remove(first); deque.addLast(nums[i]); priorityQueue.add(nums[i]); } result[result.length - 1] = priorityQueue.peek(); return result; }
/** * gives turns for buying to players * * @throws IOException exception */ private static void buyTurnIncre() throws IOException { if (playerOrder.isEmpty()) { for (Player p : Configurations.getPlayers()) { if (p.getMoney() > 300 && !p.isPassed()) { playerOrder.add(p); } } if (playerOrder.isEmpty()) { Configurations.setRound(Configurations.getRound() + 1); // Applying random event to player 1 during initial game start Configurations.getCurPlayer().setMessage(applyRandomEvent()); Configurations.getGameScreenController() .updateText(Configurations.getCurPlayer().getMessage()); Configurations.getLoopService().start(); movePhaseTurnIncre(); return; } } Configurations.setCurPlayer(playerOrder.remove()); if (Configurations.getCurPlayer().isPassed()) { buyTurnIncre(); } Configurations.getGameScreenController().updateText(); }
public static void computePaths(Vertex source, ArrayList<String> ziel) { source.minDistance = 0.; PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(source); while (!vertexQueue.isEmpty()) { Vertex u = vertexQueue.poll(); // Visit each edge exiting u for (Edge e : u.adjacencies) { Vertex v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { vertexQueue.remove(v); v.minDistance = distanceThroughU; v.previous = u; vertexQueue.add(v); } } if (ziel.contains(u.name)) { vertexQueue.clear(); break; } } }
/** Implements method from {@link IPathFinder}. */ public List<Point> findPath(Point start, Point end) { assertPointIsInBounds(start); assertPointIsInBounds(end); PriorityQueue<PathNode> openSet = new PriorityQueue<PathNode>(); Map<Point, PathNode> openSetLookupMap = new HashMap<Point, PathNode>(); Set<Point> closedSet = new HashSet<Point>(); PathNode startNode = new PathNode(null, start, 0, context.h(start, end)); openSet.add(startNode); openSetLookupMap.put(startNode.location, startNode); while (!openSet.isEmpty()) { PathNode current = openSet.remove(); openSetLookupMap.remove(current.location); if (current.location.equals(end)) { return reconstructPath(current); } closedSet.add(current.location); for (Point neighbor : findNeighbors(current.location, context.allowDiagonalMovements())) { if (!isInValidPoint(neighbor) && !closedSet.contains(neighbor)) { PathNode neighborNode = openSetLookupMap.get(neighbor); double tentativeGvalue = current.g + context.g_factor(neighbor); if (neighborNode == null) { neighborNode = new PathNode(current, neighbor, tentativeGvalue, context.h(neighbor, end)); } else { neighborNode.g = Math.min(neighborNode.g, tentativeGvalue); } // TODO modify to use HashSet instead of PriorityQueue since remove is linear anyway // TODO the above should allow us to condense two openSets into a single one, replacing // openSet.remove() w/ linear time lookup // TODO consider inserting things into self sorting data structure, that way remove is // constant time and lookups are log n (binary search?) openSet.remove(neighborNode); openSet.add(neighborNode); } } } return new ArrayList<Point>(); }
/** Picks and removes the next entry. Returns null if the entry has been removed. */ public Entry removeNext() { Entry p = pending_queue.remove(); if (!pending_set.remove(p)) { if (logger.isDebugEnabled()) logger.debug("Skipping removed entry " + p); return null; } return p; }
/*skylineII * // First: split building into two edge and sort // Second: create a max-heap with first height 0, we offer height and poll height // Third: for every edge, - put in(new skyline), + remove it(old skyline), if current max height not the same as before we add in // init 0, max height so far, if change, skyline redraw // * */ public List<int[]> skylineII(List<Interval> intervals) { List<int[]> res = new ArrayList<int[]>(); if (intervals == null || intervals.size() == 0) { return res; } // First: split building into two edge and sort List<int[]> height = new ArrayList<int[]>(); for (Interval item : intervals) { height.add(new int[] {item.start, -item.height}); // start, -height height.add(new int[] {item.end, item.height}); // end, height } Collections.sort( height, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if (a[0] != b[0]) return a[0] - b[0]; return a[1] - b[1]; // start BEFORE end, height small BEFORE height large // BOTH START -10,-5=> -10->-5 // BOTH END 10, 5=>5->10 } }); // Second: create a max-heap with first height 0, we offer height and poll height // 根据position从前到后扫描每一个edge // 将edge根据是入还是出来将当前height加入或者移除heap // 再得到当前最高点(max-heap)来决定是否加入最终结果。 // 把所有的turning points 放在一起,根据coordination从小到大sort 。 // 再用max-heap, 把所有的turning points扫一遍,遇到start turning point, // 把 volume放入max-heap. // 遇到end turning point,把对应的volume从max-heap中取出。 // max-heap的max 值就是对应区间的最大volume // Input : [2,-10][3,-15][5,-12][7,15][9,10][12,12][15,-10][19,-8][20,10][24,8] // Result: [2 10],[3 15],[7 12],[12 0],[15 10],[20 8],[24, 0] // Event{true,0,200}, Event{false,10,200} // ==> Event{0,200}, Event{10,-200} // 按照time排序,time相同,is_in = false的优先 // 然后你扫过去, is_in=true的你就加mem,is_in=false的你就-mem.每个事件点, // 你会加或减一次,每加或减一次后,就check是不是超过总的 PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10, new pqComparator()); // Avoid empty heap, still has ZERO value pq.offer(0); int prev = 0; // Third: for every edge, - put in(new skyline), + remove it(old skyline), if current max height // not the same as before we add in // init 0, max height so far, if change, skyline redraw for (int[] item : height) { // START, ADD if (item[1] < 0) pq.offer(-item[1]); // END, REMOVE else pq.remove(item[1]); int max = pq.peek(); if (prev != max) { res.add(new int[] {item[0], max}); prev = max; } } return res; }
@Override public void decreaseKey(int element, int key) { if (key < elements[element].distance) { VertexWithDistance updated = new VertexWithDistance(element, key); q.remove(updated); q.add(updated); elements[element] = updated; } }
/** * Removes a single instance of the specified element from this queue, if it is present, whether * or not it has expired. */ public boolean remove(Object o) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.remove(o); } finally { lock.unlock(); } }
public void purge() { CacheEntry queueEntry = expirationQueue.peek(); while ((queueEntry != null) && queueEntry.isExpired()) { super.remove(queueEntry.getKey()); expirationQueue.remove(); queueEntry = expirationQueue.peek(); } }
public void dijkstra(int src) { d[src] = 0; pq.add(src); while (!pq.isEmpty()) { int u = pq.remove(); for (int i = 1; i <= intersection; i++) { if (Matrix[u][i] != 0) relax(u, i, Matrix[u][i]); } } }
@Override public CacheEntry remove(Object key) { CacheEntry entry = super.remove(key); if (entry != null) { expirationQueue.remove(entry); } return entry; }
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 static void update(float tpf) { if (heap.isEmpty() == false) { myTime += (long) (tpf * 1000); while (heap.isEmpty() == false && ((Timer) heap.peek()).time < myTime) { Timer t = (Timer) heap.peek(); heap.remove(); t.execute(); } } }
private void testCustomAggregation(Long[] values, int n) { PriorityQueue<Long> heap = new PriorityQueue<Long>(n); Arrays.stream(values).filter(x -> x != null).forEach(heap::add); Long[] expected = new Long[heap.size()]; for (int i = heap.size() - 1; i >= 0; i--) { expected[i] = heap.remove(); } testAggregation( Arrays.asList(expected), createLongsBlock(values), createLongRepeatBlock(n, values.length)); }
public void clearNearestBlockade() throws SOSActionException { log.info("clearing NearestBlockade"); PriorityQueue<Blockade> blockadesInRange = model().getBlockadesInRange(agent.me().getX(), agent.me().getY(), agent.clearDistance); log.debug("Blockades in Range=" + blockadesInRange); Blockade selectedBlock = null; if (!blockadesInRange.isEmpty()) selectedBlock = blockadesInRange.remove(); log.debug("best blockade:" + selectedBlock); if (selectedBlock != null) clear(selectedBlock); }