HDU 4544

来源:互联网 发布:苏格兰折耳猫 知乎 编辑:程序博客网 时间:2024/06/05 15:53

题意就不说了。用的是贪心和优先队列吧!!!

以前优先队列用的少,不熟悉。找了些资料。


先给出代码吧!

AC:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>  //别忘了头文件using namespace std;int q[100008],n,m;struct node{int a,b;friend bool operator<(node c,node d){return c.b>d.b;}}w[100008];bool cmp(int x,int y){return x>y;}bool cmp1(node x,node y){return x.a>y.a;}priority_queue<node > e;int main(){int i,j;while(~scanf("%d%d",&n,&m)){for(i=1;i<=n;i++) scanf("%d",&q[i]);for(i=1;i<=m;i++) scanf("%d",&w[i].a);for(i=1;i<=m;i++) scanf("%d",&w[i].b);sort(q+1,q+1+n,cmp);sort(w+1,w+1+m,cmp1);if( n > m){printf("No\n");continue;}while(!e.empty()) e.pop();__int64 sum=0;j=1;for(i=1;i<=n;i++){while(j <= m && w[j].a >= q[i] ){  //把满足击杀的箭放入优先队列e.push(w[j]);j++;}if(e.empty()) break;sum+=e.top().b;e.pop();}if(i != n+1) printf("No\n");else printf("%I64d\n",sum);}return 0;}


这个是转得网上的,由于不经常使用,偶尔用的时候还经常出错,所以记下来了,经常使用的已经用红色颜色标出来了 :

在优先队列中,优先级高的元素先出队列。 优先队列插入和删除元素的复杂度都是O(log2n),所以很快。
标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
优先队列的第一种用法,也是最常用的用法:

priority_queue<int> qi;

通过<操作符可知在整数中元素大的优先级高。
故示例1中输出结果为:9 6 5 3 2

第二种方法:
在示例1中,如果我们要把元素从小到大输出怎么办呢?
这时我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。

priority_queue<int, vector<int>, greater<int> >qi2;

其中
第二个参数为容器类型。
第二个参数为比较函数。
故示例2中输出结果为:2 3 5 6 9

第三种方法:
自定义优先级。

struct node
{
    friend bool operator< (node n1, node n2)
    {
        return n1.priority < n2.priority;
    }
    int priority;
    int value;
};

在该结构中,value为值,priority为优先级。
通过自定义operator<操作符来比较元素中的优先级。
在示例3中输出结果为:
优先级  值
9          5
8          2
6          1
2          3
1          4
但如果结构定义如下:

struct node
{
    
friend bool operator> (node n1, node n2)
    {
        
return n1.priority > n2.priority;
    }
    
int priority;
    
int value;
};

则会编译不过(G++编译器)
因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
而且自定义类型的<操作符与>操作符并无直接联系,故会编译不过。

补充的一点是:

我们可以自己写一个比较类,还设定优先级:

struct cmp
{
    bool operator() (const int &a, const int &b)
    {
        return dist[a] > dist[b];
    }
};

priority_queue<int,vector<int>,cmp> q;(按照元素的dist大小从小到大排序).


原创粉丝点击