优先队列的应用,
定义优先队列:
struct node{
int d,p;
friend bool operator<(node x,node y) //优先队列
{
return x.p>y.p;
}
};
priority_queue<node> q;
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int d,p;
friend bool operator<(node x,node y) //优先队列
{
return x.p>y.p;
}
};
int b[100005];
node work[100005];
priority_queue<node> q;
int cmp(node x,node y)
{
return x.d>y.d;
}
int main()
{
int n,m;
int i,j;
while(scanf("%d%d",&n,&m)==2)
{
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<m;i++)
scanf("%d",&work[i].d);
for(i=0;i<m;i++)
scanf("%d",&work[i].p);
sort(b,b+n);
sort(work,work+m,cmp);
j=0;
bool flag=true;
__int64 sum=0;
while(!q.empty()) //清空队列
q.pop();
for(i=n-1;i>=0;i--)
{
while(j<m&&work[j].d>=b[i]) //将能杀死兔子的箭,入优先队列
{
q.push(work[j]);
j++;
}
if(q.empty())
{
flag=false;
break;
}
sum+=q.top().p;
q.pop();
}
if(!flag) printf("No\n");
else
printf("%I64d\n",sum);
}
return 0;
}
本文通过一个具体的案例展示了优先队列在解决特定问题时的应用。文章详细解释了如何使用C++实现优先队列,并通过一系列步骤说明如何用优先队列来优化算法效率,解决了兔子与箭之间的匹配问题。
274

被折叠的 条评论
为什么被折叠?



