本文整理汇总了Java中java.util.PriorityQueue.isEmpty方法的典型用法代码示例。如果您正苦于以下问题:Java PriorityQueue.isEmpty方法的具体用法?Java PriorityQueue.isEmpty怎么用?Java PriorityQueue.isEmpty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.isEmpty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: onEventTime
import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
* Occurs when an event-time timer fires due to watermark progression.
*
* @param timer the timer details.
*/
@Override
public void onEventTime(InternalTimer<K, VoidNamespace> timer) throws Exception {
long currentWatermark = internalTimerService.currentWatermark();
PriorityQueue<Long> sortedTimestamps = getSortedTimestamps();
while (!sortedTimestamps.isEmpty() && sortedTimestamps.peek() <= currentWatermark) {
long timestamp = sortedTimestamps.poll();
for (T event : elementQueueState.get(timestamp)) {
output.collect(new StreamRecord<>(event, timestamp));
}
elementQueueState.remove(timestamp);
}
if (sortedTimestamps.isEmpty()) {
elementQueueState.clear();
}
if (!sortedTimestamps.isEmpty()) {
saveRegisterWatermarkTimer();
}
}
示例2: mergeSorted
import java.util.PriorityQueue; //导入方法依赖的package包/类
public static List<Integer> mergeSorted(List<List<Integer>> sortedArrays) {
List<Iterator<Integer>> iters = new ArrayList<>(sortedArrays.size());
for (List<Integer> array : sortedArrays)
iters.add(array.iterator());
PriorityQueue<ArrayEntry> minHeap = new PriorityQueue<>(iters.size(), ArrayEntry::compareTo);
for (int i = 0; i < iters.size(); i++) {
if (iters.get(i).hasNext())
minHeap.add(new ArrayEntry(iters.get(i).next(),i));
}
List<Integer> result = new ArrayList<>();
while (!minHeap.isEmpty()) {
ArrayEntry temp = minHeap.poll();
result.add(temp.value);
if (iters.get(temp.arrayId).hasNext())
minHeap.add(new ArrayEntry(iters.get(temp.arrayId).next(),temp.arrayId));
}
return result;
}
示例3: dijkstra
import java.util.PriorityQueue; //导入方法依赖的package包/类
private void dijkstra(GraphAdjacencyListRepresentation graph) {
dist[S] = 0;
PriorityQueue<VerticePriority> pq = new PriorityQueue<>();
pq.add(new VerticePriority(S, dist[S]));
int u;
List<Integer> adjVertices, adjWeight;
while (!pq.isEmpty()) {
u = pq.poll().vertice;
int v, w;
adjVertices = graph.getAdjNode(u);
adjWeight = graph.getAdjWeight(u);
for (int i = 0; i < adjVertices.size(); i++) {
v = adjVertices.get(i);
w = adjWeight.get(i);
// relax the edge
if ((dist[v] == -1) || (dist[v] > dist[u] + w)) {
dist[v] = dist[u] + w;
prev[v] = u;
pq.add(new VerticePriority(v, dist[v]));
}
}
}
}
示例4: main
import java.util.PriorityQueue; //导入方法依赖的package包/类
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
/* Create PriorityQueue and add/remove entries */
PriorityQueue<Student> pq = new PriorityQueue<>(n, new StudentComparator());
while (n-- > 0) {
String event = scan.next();
switch (event) {
case "ENTER":
String fname = scan.next();
double cgpa = scan.nextDouble();
int token = scan.nextInt();
pq.add(new Student(fname, cgpa, token));
break;
case "SERVED":
pq.poll();
break;
default:
break;
}
}
scan.close();
/* Print Student names */
if (pq.isEmpty()) {
System.out.println("EMPTY");
} else {
while (!pq.isEmpty()) {
Student s = pq.remove();
System.out.println(s.getFname());
}
}
}
示例5: getShortestPathsIntern
import java.util.PriorityQueue; //导入方法依赖的package包/类
@Override
protected List<List<E>> getShortestPathsIntern(final V source,
final V target, int k) {
LinkedList<List<E>> found_paths = new LinkedList<List<E>>();
PriorityQueue<WeightedPath> prioQ = new PriorityQueue<WeightedPath>();
DijkstraShortestPath<V, E> blockedDijkstra;
// Check if target is reachable from source.
if (dijkstra.getDistance(source, target) == null)
return found_paths;
// Add Dijkstra solution, the first shortest path.
found_paths.add(dijkstra.getPath(source, target));
while (found_paths.size() < k) {
List<E> curShortestPath = found_paths.getLast();
int maxIndex = curShortestPath.size();
// Split path into Head and NextEdge
for (int i = 0; i < maxIndex; i++) {
List<E> head = curShortestPath.subList(0, i /* excluded */);
V deviation = head.isEmpty() ? source : graph.getDest(head
.get(i - 1));
// 1. Block edges.
Graph<V, E> blocked = blockFilter(head, deviation, found_paths);
// 2. Get shortest path in graph with blocked edges.
blockedDijkstra = new DijkstraShortestPath<V, E>(blocked, nev);
Number dist = blockedDijkstra.getDistance(deviation, target);
if (dist == null)
continue;
List<E> tail = blockedDijkstra.getPath(deviation, target);
// 3. Combine head and tail into new path.
List<E> candidate = new ArrayList<E>(i + tail.size());
candidate.addAll(head);
candidate.addAll(tail);
// Check if we already found this solution
boolean duplicate = false;
for (WeightedPath path : prioQ)
if (ListUtils.isEqualList(path.getPath(), candidate)) {
duplicate = true;
break;
}
if (!duplicate)
prioQ.add(new WeightedPath(candidate));
}
if (prioQ.isEmpty())
break; // We have not found any new candidate!
else
found_paths.add(prioQ.poll().getPath());
}
return found_paths;
}
示例6: getShortestPathsIntern
import java.util.PriorityQueue; //导入方法依赖的package包/类
@Override
protected List<List<E>> getShortestPathsIntern(V source, V target, int k) {
PriorityQueue<WeightedPath> prioQ = new PriorityQueue<WeightedPath>();
List<List<E>> found_paths = new LinkedList<List<E>>();
Transformer<E, Double> delta = prepareTransformations(target);
// Initialize with start vertex.
prioQ.add(new WeightedPath(source));
while (!prioQ.isEmpty() && found_paths.size() < k) {
WeightedPath curPath = prioQ.poll(); // get & remove next shortest
V curV = curPath.getLast();
if (curV.equals(target)) {
found_paths.add(curPath.getPath());
continue;
}
// Create new paths for every expanded vertex ...
for (V nextV : graph.getSuccessors(curV)) {
if (curPath.contains(nextV))
continue; // Prevent looping!
// ... and every possible edge.
for (E e : graph.findEdgeSet(curV, nextV)) {
if (Double.isInfinite(delta.transform(e)))
continue; // Skip unreachable vertices.
WeightedPath tmpPath = new WeightedPath(curPath); // clone
tmpPath.addHop(e, delta.transform(e), nextV);
prioQ.add(tmpPath);
}
}
}
return found_paths;
}
示例7: computePathsDGM
import java.util.PriorityQueue; //导入方法依赖的package包/类
private ConditionVertex computePathsDGM(){
PriorityQueue<ConditionVertex> openSet = new PriorityQueue<ConditionVertex>();
this.source.distance = 0;
openSet.add(this.source);
int operations = 0;
System.out.println("openset at start: " + openSet);
while(!openSet.isEmpty() && operations < OPERATIONCOUNT_THRESHOLD){
System.out.println("operationsloop");
ConditionVertex u = openSet.poll();
if(u.depth == generalizedGoalList.size()){
return u;
}
int numberOfAdjacenciesBefore = u.adjacencies.size();
u.expandNodeDGM(generalizedGoalList.get(u.depth));
int numberOfAdjacenciesAfter = u.adjacencies.size();
//if goal is not expandable for the next generalizedGoal in the list
//the loop has to continue with the next
if(numberOfAdjacenciesBefore == numberOfAdjacenciesAfter){
continue;
} else {
for (ProbabilityEdge e : u.adjacencies){
operations++;
ConditionVertex v = e.target;
v.prev = u;
double eventDistance = e.weight;
double newDistanceToV = u.distance + eventDistance;
// check if new likelihood is greater
openSet.add(v);
}
}
}
return null;
}
示例8: shortestPath
import java.util.PriorityQueue; //导入方法依赖的package包/类
public void shortestPath(int source, int destination) {
Set<Node> visited = new HashSet<>();
PriorityQueue<Node> pQueue = new PriorityQueue<>(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o1.cost - o2.cost;
}
});
nodes[source].cost = 0;
pQueue.add(nodes[source]);
while(!pQueue.isEmpty()) {
Node currVertex = pQueue.poll();
for(int i = 0; i < graph.length; i++) {
if(graph[currVertex.id][i]!=0 && !visited.contains(nodes[i]) ) {
if(!pQueue.contains(nodes[i])) {
nodes[i].cost = currVertex.cost + graph[currVertex.id][i];
nodes[i].parent = currVertex;
pQueue.add(nodes[i]);
}
else {
nodes[i].cost = Math.min(nodes[i].cost, currVertex.cost + graph[currVertex.id][i]);
if(nodes[i].cost == currVertex.cost + graph[currVertex.id][i])
nodes[i].parent = currVertex;
}
}
}
visited.add(currVertex);
}
}
示例9: computeCodeEmittingOrder
import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
* Iteratively adds paths to the code emission block order.
*/
private static <T extends AbstractBlockBase<T>> void computeCodeEmittingOrder(List<T> order, PriorityQueue<T> worklist, BitSet visitedBlocks) {
while (!worklist.isEmpty()) {
T nextImportantPath = worklist.poll();
addPathToCodeEmittingOrder(nextImportantPath, order, worklist, visitedBlocks);
}
}
示例10: toIntArrayListReversed
import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
* Used in cases where a priority queue has been used to keep top K elements, and then its results are needed in descending order,
* in the form of an IntArrayList. The size of the results is equal to the size of the input.
* @param <T> any subclass of ComparableIntFloatPair
* @param pq
* @return
*/
public static <T extends ComparableIntFloatPair> IntArrayList toIntArrayListReversed(PriorityQueue<T> pq) {
int i = pq.size();
int[] candidates = new int[i];
while (!pq.isEmpty()) {
T cand = pq.poll();
candidates[--i] = cand.getEntityId(); //get pq elements in reverse order
}
return new IntArrayList(candidates);
}
示例11: main
import java.util.PriorityQueue; //导入方法依赖的package包/类
@SuppressWarnings("Duplicates")
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PriorityQueue<Integer> minHeap = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(10);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();
if (minHeap.size() <= maxHeap.size()) {
minHeap.add(num);
} else {
maxHeap.add(num);
}
while (!minHeap.isEmpty() && !maxHeap.isEmpty() && minHeap.peek() > maxHeap.peek()) {
int min = minHeap.poll();
int max = maxHeap.poll();
minHeap.add(max);
maxHeap.add(min);
}
double median = (minHeap.size() == maxHeap.size() ? ((minHeap.peek() + maxHeap.peek()) / 2.0) : minHeap.peek());
System.out.println(median);
}
}
示例12: bidirectionalDijkstra
import java.util.PriorityQueue; //导入方法依赖的package包/类
private void bidirectionalDijkstra(GraphAdjacencyListRepresentation graph) {
GraphAdjacencyListRepresentation reverseGraph = graph.reverseGraph();
dist[S] = 0;
distR[T] = 0;
PriorityQueue<VerticePriority> pq = new PriorityQueue<>();
pq.add(new VerticePriority(S, dist[S]));
PriorityQueue<VerticePriority> pqR = new PriorityQueue<>();
pqR.add(new VerticePriority(T, dist[T]));
while ((!pq.isEmpty()) || (!pqR.isEmpty())) {
int u, v, w;
List<Integer> adjVertices, adjWeight;
// forward
if (!pq.isEmpty()) {
u = pq.poll().vertice;
adjVertices = graph.getAdjNode(u);
adjWeight = graph.getAdjWeight(u);
for (int i = 0; i < adjVertices.size(); i++) {
v = adjVertices.get(i);
w = adjWeight.get(i);
// relax a forward edge
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
prev[v] = u;
pq.add(new VerticePriority(v, dist[v]));
}
}
proc.add(u);
if (procR.contains(u)) {
computeShortestPath();
break;
}
}
// backward
if (!pqR.isEmpty()) {
u = pqR.poll().vertice;
adjVertices = reverseGraph.getAdjNode(u);
adjWeight = reverseGraph.getAdjWeight(u);
for (int i = 0; i < adjVertices.size(); i++) {
v = adjVertices.get(i);
w = adjWeight.get(i);
// relax a backward edge
if (distR[v] > distR[u] + w) {
distR[v] = distR[u] + w;
prevR[v] = u;
pqR.add(new VerticePriority(v, distR[v]));
}
}
procR.add(u);
if (proc.contains(u)) {
computeShortestPath();
break;
}
}
}
}
开发者ID:MiguelSteph,项目名称:data-structures-and-algorithm,代码行数:67,代码来源:ShortestPathWithBidirectionalDijkstra.java
示例13: findShortestPath
import java.util.PriorityQueue; //导入方法依赖的package包/类
private static SearchNode findShortestPath(List<SearchNode> nodes, Set<Location> pathLocs, AvoidanceMap avoid) {
PriorityQueue<SearchNode> q = new PriorityQueue<SearchNode>(nodes);
HashSet<SearchNode> visited = new HashSet<SearchNode>();
int iters = 0;
while (!q.isEmpty() && iters < MAX_SEARCH_ITERATIONS) {
iters++;
SearchNode n = q.remove();
if (iters % 64 == 0 && ConnectorThread.isOverrideRequested() || n == null) {
return null;
}
if (n.isDestination()) {
return n;
}
boolean added = visited.add(n);
if (!added) {
continue;
}
Location loc = n.getLocation();
Direction dir = n.getDirection();
int neighbors = 3;
Object allowed = avoid.get(loc);
if (allowed != null && n.isStart() && pathLocs.contains(loc)) {
allowed = null;
}
if (allowed == ALLOW_NEITHER) {
neighbors = 0;
} else if (allowed == ALLOW_VERTICAL) {
if (dir == null) {
dir = Direction.NORTH;
neighbors = 2;
} else if (dir == Direction.NORTH || dir == Direction.SOUTH) {
neighbors = 1;
} else {
neighbors = 0;
}
} else if (allowed == ALLOW_HORIZONTAL) {
if (dir == null) {
dir = Direction.EAST;
neighbors = 2;
} else if (dir == Direction.EAST || dir == Direction.WEST) {
neighbors = 1;
} else {
neighbors = 0;
}
} else {
if (dir == null) {
dir = Direction.NORTH;
neighbors = 4;
} else {
neighbors = 3;
}
}
for (int i = 0; i < neighbors; i++) {
Direction oDir;
switch (i) {
case 0:
oDir = dir;
break;
case 1:
oDir = neighbors == 2 ? dir.reverse() : dir.getLeft();
break;
case 2:
oDir = dir.getRight();
break;
default: // must be 3
oDir = dir.reverse();
}
SearchNode o = n.next(oDir, allowed != null);
if (o != null && !visited.contains(o)) {
q.add(o);
}
}
}
return null;
}
示例14: findPathTo
import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
* Precondition: the unit has enough mobility to reach the Terrain that the path is being found to.
* The returned path will be optimal, uses A*
*
* @return a queue of Terrains that could be traversed to reach the destination
* @throws Exception
*/
private Queue<Terrain> findPathTo(Terrain target) throws Exception {
Queue<Terrain> ans = new LinkedList<>();
if (null == target) {
return new LinkedList<>();
}
if (target == getLocation()) {
//you are already here
return ans;
}
Map<Terrain, Terrain> previousLink = new HashMap<>();
previousLink.put((Terrain) getLocation(), null);
@SuppressWarnings({"unchecked", "rawtypes"})
Comparator<Terrain> comp = new Comparator() {
@Override
/**
* Approximates which path is better
*/
public int compare(Object o1, Object o2) {
Terrain t1 = (Terrain) o1;
Terrain t2 = (Terrain) o2;
// Integer c1 = totalCost(savedPaths.get(t1))+t1.getDistanceTo(target);
// Integer c2 = totalCost(savedPaths.get(t2))+t2.getDistanceTo(target);
Integer c1 = totalCost(t1, previousLink) + t1.getDistanceTo(target);
Integer c2 = totalCost(t2, previousLink) + t2.getDistanceTo(target);
return c1.compareTo(c2);
}
};
PriorityQueue<Terrain> toCheck = new PriorityQueue<>(comp);
toCheck.add((Terrain) getLocation());
while (!toCheck.isEmpty()) {
Terrain current = toCheck.poll();
for (Terrain t : current.getAllAdjacentTerrains()) {
if (999 != t.getMoveCost(getMovementType()) &&
(null == getGrid().get(t) || ((Unit) (getGrid().get(t))).getOwner() == this.getOwner())) {
boolean updated = false;
if (!previousLink.containsKey(t)) {
previousLink.put(t, current);
updated = true;
}
if (t == target) {
return genPath(t, previousLink);
}
if (t.getMoveCost(getMovementType()) + totalCost(current, previousLink) < totalCost(t, previousLink)) {
previousLink.put(t, current);
updated = true;
}
if (totalCost(t, previousLink) <= getCurrentMobility() && updated) {
if (!toCheck.contains(t)) {
toCheck.add(t);
}
}
}
}
}
//if you got here, then there is no path
//See Precondition: there is a path, checked by getValidMoveSpaces
throw new Exception("no path, precondition not met");
}
示例15: reduceScopeAlleles
import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
* Returns a the new set of alleles to use.
* @param vc target variant context.
* @param numAllelesToChoose number of alleles to keep.
* @return the list of alternative allele to keep.
*/
protected List<Allele> reduceScopeAlleles(final VariantContext vc, final int defaultPloidy, final int numAllelesToChoose) {
// Look for the <NON_REF> allele to exclude it from the pruning if present.
final int numOriginalAltAlleles = vc.getAlternateAlleles().size();
final int nonRefAltAlleleIndex = GATKVariantContextUtils.indexOfAltAllele(vc,
GATKVariantContextUtils.NON_REF_SYMBOLIC_ALLELE, false);
final boolean nonRefAltAllelePresent = nonRefAltAlleleIndex >= 0;
// <NON_REF> should not be considered in the downsizing, so we need to count it out when
// considering if alt. allele downsizing is required.
final int numProperOriginalAltAlleles = numOriginalAltAlleles - (nonRefAltAllelePresent ? 1 : 0);
// Avoid pointless allele reduction:
if (numAllelesToChoose >= numProperOriginalAltAlleles)
return vc.getAlternateAlleles();
final LikelihoodSum[] likelihoodSums = new LikelihoodSum[numOriginalAltAlleles];
for ( int i = 0; i < numOriginalAltAlleles; i++ ) {
final Allele allele = vc.getAlternateAllele(i);
likelihoodSums[i] = new LikelihoodSum(allele,i);
}
// Calculate the allele likelihood sums.
reduceScopeCalculateLikelihoodSums(vc, defaultPloidy, likelihoodSums);
// sort them by probability mass and choose the best ones
// Make sure that the <NON_REF> allele is last if present.
Collections.sort(Arrays.asList(likelihoodSums), nonRefAltAllelePresent ? LIKELIHOOD_NON_REF_THEN_SUM_COMPARATOR : LIKELIHOOD_SUM_COMPARATOR);
// We need to return the best likelihood alleles in the original alternative allele index order.
// This heap will keep track of that index order.
final PriorityQueue<LikelihoodSum> mostLikelyAllelesHeapByIndex = new PriorityQueue<>(numOriginalAltAlleles, LIKELIHOOD_INDEX_COMPARATOR);
for ( int i = 0; i < numAllelesToChoose; i++ )
mostLikelyAllelesHeapByIndex.add(likelihoodSums[i]);
// guaranteed no to have been added at this point thanks for checking on whether reduction was
// needed in the first place.
if (nonRefAltAllelePresent)
mostLikelyAllelesHeapByIndex.add(likelihoodSums[nonRefAltAlleleIndex]);
final ArrayList<Allele> orderedBestAlleles = new ArrayList<>(numAllelesToChoose);
while (!mostLikelyAllelesHeapByIndex.isEmpty())
orderedBestAlleles.add(mostLikelyAllelesHeapByIndex.remove().allele);
return orderedBestAlleles;
}