题目链接:HDU 4544
一个需要用到优先队列的题 ,这里需要用到自定义优先队列的优先级,优先队列的优先级与sort是相反的,less<>表示大的优先,greater<>表示小的优先,重载小于运算符的时候,a>b在sort里面表示从大到小排列,在优先队列里面表示小的优先弹出,这里关于重载运算符介绍了三种写法,这也是我第一次用优先队列,把兔子血量从大到小排序,把大于兔子血量的箭压进队列 然后依次让价钱最低的弹出...这就是具体思路
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define N 100005
struct node
{
int h;
int q;//const保证,在函数作用域内不会修改 node 的值,只交换了位置;&表示传进来的只是引用,可以理解为指针,而不是把node的所有值复制进来,可以节省时间
/*friend bool operator<(const node &x,const node &y)
{
return x.q>y.q;//小的优先
}第一种写法,重载运算符写到结构体里面,默认less重载小于运算符,这里需要加上friend*/
}j[N];
/*bool operator<(const node &x,const node &y)
{
return x.q>y.q;
} 第二种写法,就是写到结构体外面,不需要加friend,默认less重载小于运算符,只是重载node型的排序或者优先,别的类型还是默认函数*/
struct cmpn
{
bool operator()(const node &x,const node &y)
{
return x.q>y.q;
}
};//第三种写法,这里写了一个伪函数cmpn,类似于less,注意格式
bool cmp(node x,node y)
{
return x.h>y.h;
}
bool cmp1(int x,int y)
{
return x>y;
}
int main()
{
int m,n,i,s[N],flag,t,temp;
while(scanf("%d %d",&m,&n)!=EOF)
{
priority_queue <node,vector<node>,cmpn> x;
//前两种这里这样写priority_queue <node,vector<node>,less<node> > x;或者只要<node>
for(i=0;i<m;i++)
scanf("%d",&s[i]);
for(i=0;i<n;i++)
scanf("%d",&j[i].h);
for(i=0;i<n;i++)
scanf("%d",&j[i].q);
sort(s,s+m,cmp1);
sort(j,j+n,cmp);
long long num=0;
flag=1;
t=0;
for(i=0;i<m;i++)
{
while(t<n&&j[t].h>=s[i])
{
x.push(j[t]);
t++;
}
if(x.empty())
{
flag=0;
break;
}
else
{
temp=x.top().q;
num+=temp;
x.pop();
}
}
if(flag==0)
printf("No\n");
else
printf("%lld\n",num);
}
return 0;
}