java 优先队列 用法_优先队列的基本用法(java和c++)
#include
#define ll long long
#define mod 1000000007
using namespace std;
//熟悉一下優(yōu)先隊(duì)列的基本用法
int main()
{
int n;cin>>n;
priority_queueq;
int j;
for(int i=1;i<=n;i++)
{
cin>>j;
q.push(j);
}
while(!q.empty())
{
cout<
q.pop();
}
return 0;
}
java:
import java.math.BigInteger;
import java.util.*;
public class CF470C {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
queue.add("C");
queue.add("C++");
queue.add("Python");
queue.add("Java");
// Printing the most priority element
System.out.println("Head value using peek function:"
+queue.peek());
// Printing all elements
System.out.println("The queue elements");
Iterator itr=queue.iterator();
while(itr.hasNext())
System.out.println(itr.next());
// Removing the top priority element (or head) and
// printing the modified pQueue
queue.poll();
System.out.println("After removing an element" +
"with poll function:");
Iterator itr2 = queue.iterator();
while (itr2.hasNext())
System.out.println(itr2.next());
// // Removing Java
queue.remove("C");
System.out.println("after removing Java with" +
" remove function:");
Iterator itr3 = queue.iterator();
while (itr3.hasNext())
System.out.println(itr3.next());
// // Check if an element is present
boolean b=queue.contains("C");
System.out.println ( "Priority queue contains C" +
"ot not?: " + b);
// get objects from the queue in an array and
// print the array
Object[]arr=queue.toArray();
System.out.println("Value in array: ");
for(int i=0;i
System.out.println("Value: "+arr[i].toString());
}
}
注意:Java中的優(yōu)先隊(duì)列沒有排序功能,若要排序,請(qǐng)用:
As you?can?see in the PriorityQueue javadoc: The Iterator provided in method iterator()?is?not guaranteed to traverse the elements of the?priority queue?in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). That's because?java.util.PriorityQueue implements a binary heap.
應(yīng)用:
Applications :
Implementing Dijkstra’s and Prim’s algorithms.
https://www.geeksforgeeks.org/priority-queue-class-in-java-2/
例題:
//��CF 947B
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
typedef double DB;
const int N = 111111;
int n,a[N],b[N];
priority_queue,greater > Q;
int main()
{
int i,x;
LL w,ans;
scanf("%d",&n);
for(i=1;i<=n;i=i+1)
scanf("%d",a+i);
for(i=1;i<=n;i=i+1)
scanf("%d",b+i);
w=0,x=0;
for(i=1;i<=n;i=i+1){
ans=0;
Q.push(w+a[i]);
x++;
while(!Q.empty()&&Q.top()<=w+b[i]){
ans+=Q.top()-w;
Q.pop();
x--;
}
w+=b[i];
ans+=(LL)b[i]*x;
cout<
}
return 0;
}
總結(jié)
以上是生活随笔為你收集整理的java 优先队列 用法_优先队列的基本用法(java和c++)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java creat uid_关于uni
- 下一篇: java 俄语 工作_工作俄语怎么说