当前位置: 首页>>代码示例>>Java>>正文


Java PriorityQueue类代码示例

本文整理汇总了Java中java.util.PriorityQueue的典型用法代码示例。如果您正苦于以下问题:Java PriorityQueue类的具体用法?Java PriorityQueue怎么用?Java PriorityQueue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PriorityQueue类属于java.util包,在下文中一共展示了PriorityQueue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import java.util.PriorityQueue; //导入依赖的package包/类
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()){
        int n = sc.nextInt();
        int minPower = 0;
        Queue<Integer> queue = new PriorityQueue<>();

        for(int i=0; i<n; i++){
            queue.add(sc.nextInt());
        }

        int first = 0, second = 0, temp = 0;
        while (queue.size() > 1){
            first = queue.poll();
            second = queue.poll();
            temp = first + second;
            queue.add(temp);

            minPower += temp;
        }
        System.out.println(minPower);
    }
}
 
开发者ID:mayuanucas,项目名称:51nod,代码行数:24,代码来源:Solution.java

示例2: split

import java.util.PriorityQueue; //导入依赖的package包/类
public static List<Geometry> split(Geometry given, double maxArea, Predicate<Geometry> predicate) {
    List<Geometry> others = newArrayList();
    PriorityQueue<Geometry> queue = new PriorityQueue<>(comparing(Geometry::getArea).reversed());
    queue.add(given);

    while (queue.peek().getEnvelope().getArea() > maxArea) {
        Geometry current = queue.poll();
        Point centroid = current.getCentroid();
        Geometry bbox = current.getEnvelope();
        checkState(bbox.getCoordinates().length == 5);
        for (int i = 0; i < 4; i++) {
            Geometry intersection = current.intersection(box(centroid, bbox.getCoordinates()[i]));
            if (!intersection.isEmpty()) {
                if (predicate.test(intersection)) {
                    others.add(intersection);
                }
                else {
                    queue.add(intersection);
                }
            }
        }
    }

    return ImmutableList.<Geometry> builder().addAll(newArrayList(queue)).addAll(others).build();
}
 
开发者ID:Mappy,项目名称:fpm,代码行数:26,代码来源:LargePolygonSplitter.java

示例3: forEachRemaining

import java.util.PriorityQueue; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> action) {
    Objects.requireNonNull(action);
    PriorityQueue<E> q = pq;
    if (fence < 0) { fence = getSize(q); expectedModCount = getModCount(q); }
    Object[] a = getQueue(q);
    int i, hi; E e;
    for (i = index, index = hi = fence; i < hi; i++) {
        if ((e = (E) a[i]) == null) {
            break;      // must be CME
        }
        action.accept(e);
    }
    if (getModCount(q) != expectedModCount) {
        throw new ConcurrentModificationException();
    }
}
 
开发者ID:retrostreams,项目名称:android-retrostreams,代码行数:19,代码来源:PQueueSpliterator.java

示例4: createPriorityQueue

import java.util.PriorityQueue; //导入依赖的package包/类
/**
 * 
 * @param distances
 * @return
 */
private PriorityQueue<Node> createPriorityQueue(final Map<Node, Integer> distances) {
    return new PriorityQueue<Node>(
            distances.size(),
            new Comparator<Node>() {

                public int compare(Node o1, Node o2) {
                    int d1 = distances.get(o1);
                    int d2 = distances.get(o2);

                    if (d1 < d2) {
                        return -1;
                    }
                    if (d1 == d2) {
                        return 0;
                    }
                    return 1;
                }

                @Override
                public boolean equals(Object obj) {
                    return this == obj;
                }
            });
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:30,代码来源:MinimumBendOrthogonalizer.java

示例5: main

import java.util.PriorityQueue; //导入依赖的package包/类
public static void main(String[] args) {
    final Comparator<String> firstChar = new Comparator<>() {
        public int compare(String x, String y) {
            return x.charAt(0) - y.charAt(0); }};

    test(new PriorityQueue<String>(firstChar));
    test(new PriorityQueue<String>(10, firstChar));
    test(new PriorityBlockingQueue<String>(10, firstChar));
    test(new ArrayBlockingQueue<String>(10));
    test(new LinkedBlockingQueue<String>(10));
    test(new LinkedBlockingDeque<String>(10));
    test(new LinkedTransferQueue<String>());
    test(new ArrayDeque<String>(10));

    System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
    if (failed > 0) throw new Error("Some tests failed");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:RemoveContains.java

示例6: getObject

import java.util.PriorityQueue; //导入依赖的package包/类
public Object getObject(CmdExecuteHelper cmdHelper) throws Exception {
  
	final Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());
	// mock method name until armed
	final BeanComparator comparator = new BeanComparator("lowestSetBit");

	// create queue with numbers and basic comparator
	final PriorityQueue<Object> queue = new PriorityQueue<Object>(2, comparator);
	// stub data for replacement later
	queue.add(new BigInteger("1"));
	queue.add(new BigInteger("1"));

	// switch method called by comparator
	Reflections.setFieldValue(comparator, "property", "outputProperties");

	// switch contents of queue
	final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
	queueArray[0] = templates;
	queueArray[1] = templates;

	return queue;
}
 
开发者ID:pimps,项目名称:ysoserial-modified,代码行数:23,代码来源:CommonsBeanutils1.java

示例7: 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]));
            }
        }
    }
}
 
开发者ID:MiguelSteph,项目名称:data-structures-and-algorithm,代码行数:24,代码来源:ShortestPathWithDijkstra.java

示例8: getBestResults

import java.util.PriorityQueue; //导入依赖的package包/类
public static List<Classifier.Recognition> getBestResults(float[] confidenceLevels, String[] labels) {
    // Find the best classifications.
    PriorityQueue<Classifier.Recognition> pq = new PriorityQueue<>(MAX_BEST_RESULTS,
            new Comparator<Classifier.Recognition>() {
                @Override
                public int compare(Classifier.Recognition lhs, Classifier.Recognition rhs) {
                    // Intentionally reversed to put high confidence at the head of the queue.
                    return Float.compare(rhs.getConfidence(), lhs.getConfidence());
                }
            });

    for (int i = 0; i < confidenceLevels.length; ++i) {
        if (confidenceLevels[i] > RESULT_CONFIDENCE_THRESHOLD) {
            pq.add(new Classifier.Recognition("" + i, labels[i], confidenceLevels[i]));
        }
    }

    ArrayList<Classifier.Recognition> recognitions = new ArrayList<Classifier.Recognition>();
    int recognitionsSize = Math.min(pq.size(), MAX_BEST_RESULTS);
    for (int i = 0; i < recognitionsSize; ++i) {
        recognitions.add(pq.poll());
    }
    return recognitions;
}
 
开发者ID:FoxLabMakerSpace,项目名称:SIGHT-For-the-Blind,代码行数:25,代码来源:Helper.java

示例9: insertMoves

import java.util.PriorityQueue; //导入依赖的package包/类
private void insertMoves() {
  SpillMoveSet spillMoves =
      new SpillMoveSet(this, code, numberOfArgumentRegisters + NUMBER_OF_SENTINEL_REGISTERS);
  for (LiveIntervals intervals : liveIntervals) {
    if (intervals.hasSplits()) {
      LiveIntervals current = intervals;
      PriorityQueue<LiveIntervals> sortedChildren =
          new PriorityQueue<>((o1, o2) -> Integer.compare(o1.getStart(), o2.getStart()));
      sortedChildren.addAll(current.getSplitChildren());
      for (LiveIntervals split = sortedChildren.poll();
          split != null;
          split = sortedChildren.poll()) {
        int position = split.getStart();
        spillMoves.addSpillOrRestoreMove(toGapPosition(position), split, current);
        current = split;
      }
    }
  }

  resolveControlFlow(spillMoves);
  firstParallelMoveTemporary = maxRegisterNumber + 1;
  maxRegisterNumber += spillMoves.scheduleAndInsertMoves(maxRegisterNumber + 1);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:24,代码来源:LinearScanRegisterAllocator.java

示例10: LightWeightCache

import java.util.PriorityQueue; //导入依赖的package包/类
@VisibleForTesting
LightWeightCache(final int recommendedLength,
    final int sizeLimit,
    final long creationExpirationPeriod,
    final long accessExpirationPeriod,
    final Clock clock) {
  super(updateRecommendedLength(recommendedLength, sizeLimit));

  this.sizeLimit = sizeLimit;

  if (creationExpirationPeriod <= 0) {
    throw new IllegalArgumentException("creationExpirationPeriod = "
        + creationExpirationPeriod + " <= 0");
  }
  this.creationExpirationPeriod = creationExpirationPeriod;

  if (accessExpirationPeriod < 0) {
    throw new IllegalArgumentException("accessExpirationPeriod = "
        + accessExpirationPeriod + " < 0");
  }
  this.accessExpirationPeriod = accessExpirationPeriod;

  this.queue = new PriorityQueue<Entry>(
      sizeLimit > 0? sizeLimit + 1: 1 << 10, expirationTimeComparator);
  this.clock = clock;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:27,代码来源:LightWeightCache.java

示例11: initializeAttributes

import java.util.PriorityQueue; //导入依赖的package包/类
protected void initializeAttributes() throws AlgorithmExecutionException {
	this.numColumns = this.columnNames.size();
	
	this.attributeId2attributeObject = new Int2ObjectOpenHashMap<Attribute>(this.numColumns);
	this.attributeObjectQueue = new PriorityQueue<Attribute>(this.numColumns);
	
	for (int table = 0; table < this.tableNames.length; table++) {
		int firstAttribute = this.tableColumnStartIndexes[table];
		int lastAttribute = (table == this.tableNames.length - 1) ? this.numColumns : this.tableColumnStartIndexes[table + 1];
		
		for (int attribute = firstAttribute; attribute < lastAttribute; attribute++) {
			Attribute spiderAttribute;
			if (this.databaseConnectionGenerator != null)
				spiderAttribute = new Attribute(attribute, this.columnTypes, this.databaseConnectionGenerator, this.inputRowLimit, this.dao, this.tableNames[table], this.columnNames.get(attribute), this.tempFolder);
			else
				spiderAttribute = new Attribute(attribute, this.columnTypes, this.fileInputGenerator[table], this.inputRowLimit, attribute - firstAttribute, this.tempFolder, this.maxMemoryUsage, this.memoryCheckFrequency);
			this.attributeId2attributeObject.put(attribute, spiderAttribute);
			
			if (!spiderAttribute.hasFinished())
				this.attributeObjectQueue.add(spiderAttribute);
		}
	}
}
 
开发者ID:HPI-Information-Systems,项目名称:metanome-algorithms,代码行数:24,代码来源:SPIDER.java

示例12: selectInputStreams

import java.util.PriorityQueue; //导入依赖的package包/类
/**
 * In this function, we get a bunch of streams from all of our JournalManager
 * objects.  Then we add these to the collection one by one.
 * 
 * @param streams          The collection to add the streams to.  It may or 
 *                         may not be sorted-- this is up to the caller.
 * @param fromTxId         The transaction ID to start looking for streams at
 * @param inProgressOk     Should we consider unfinalized streams?
 */
@Override
public void selectInputStreams(Collection<EditLogInputStream> streams,
    long fromTxId, boolean inProgressOk) throws IOException {
  final PriorityQueue<EditLogInputStream> allStreams = 
      new PriorityQueue<EditLogInputStream>(64,
          EDIT_LOG_INPUT_STREAM_COMPARATOR);
  for (JournalAndStream jas : journals) {
    if (jas.isDisabled()) {
      LOG.info("Skipping jas " + jas + " since it's disabled");
      continue;
    }
    try {
      jas.getManager().selectInputStreams(allStreams, fromTxId, inProgressOk);
    } catch (IOException ioe) {
      LOG.warn("Unable to determine input streams from " + jas.getManager() +
          ". Skipping.", ioe);
    }
  }
  chainAndMakeRedundantStreams(streams, allStreams, fromTxId);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:30,代码来源:JournalSet.java

示例13: processElement

import java.util.PriorityQueue; //导入依赖的package包/类
@Override
public void processElement(AisMessage message, Context context, Collector<AisMessage> out)
    throws Exception {

  TimerService timerService = context.timerService();

  PriorityQueue<AisMessage> queue = queueState.value();
  if (queue == null) {
    queue =
        new PriorityQueue<>(MAX_NUMBER_OF_QUEUED_ELEMENTS + 1, new PositionMessagesComparator());
  }
  long timestamp = System.currentTimeMillis();
  if (context.timestamp() > timerService.currentWatermark()) {
    queue.add(message);
    queueState.update(queue);
    // register a timer to be fired when the watermark passes this message timestamp
    timerService.registerEventTimeTimer(timestamp);
  } else {
    // logger.info("out of order message: " + message.toString());
    // throw new Exception(timerService.currentWatermark() + "out of order message: "
    // + message.toString());
    queue.add(message);
    queueState.update(queue);

  }
}
 
开发者ID:ehabqadah,项目名称:in-situ-processing-datAcron,代码行数:27,代码来源:AisMessagesStreamSorter.java

示例14: getObject

import java.util.PriorityQueue; //导入依赖的package包/类
public Queue<Object> getObject(final String command) throws Exception {
	final Object templates = Gadgets.createTemplatesImpl(command);
	// mock method name until armed
	final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]);

	// create queue with numbers and basic comparator
	final PriorityQueue<Object> queue = new PriorityQueue<Object>(2,new TransformingComparator(transformer));
	// stub data for replacement later
	queue.add(1);
	queue.add(1);

	// switch method called by comparator
	Reflections.setFieldValue(transformer, "iMethodName", "newTransformer");

	// switch contents of queue
	final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
	queueArray[0] = templates;
	queueArray[1] = 1;

	return queue;
}
 
开发者ID:hucheat,项目名称:APacheSynapseSimplePOC,代码行数:22,代码来源:CommonsCollections2.java

示例15: peekCustomerByOffice

import java.util.PriorityQueue; //导入依赖的package包/类
public QCustomer peekCustomerByOffice(QOffice office) {
    //QLog.l().logQUser().debug("peekCustomerByOffice: " + office);

    //  CM:  Get a list of all customers wanting this service.
    PriorityQueue<QCustomer> customers = getCustomers();
    QCustomer customer = null;

    //  CM:  Loop through all customers to see if they are in the office input.   
    for (Iterator<QCustomer> itr = customers.iterator(); itr.hasNext(); ) {
        final QCustomer cust = itr.next();
        //  QLog.l().logQUser().debug("Polling customer: " + cust);
        // QLog.l().logQUser().debug("  Office: " + cust.getOffice());
        // QLog.l().logQUser().debug(" Service: " + cust.getService().name);
        if (cust.getOffice().equals(office)) {
            customer = cust;
            break;
        }
    }

    return customer;
}
 
开发者ID:bcgov,项目名称:sbc-qsystem,代码行数:22,代码来源:QService.java


注:本文中的java.util.PriorityQueue类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。