济南学习D1T5__HEAP

死亡

【问题描述】

现在有个位置可以打sif,有个人在排队等着打sif。现在告诉你前个人每个人需要多长的时间打sif,问你第个人什么时候才能打sif。(前个人必须按照顺序来)

【输入格式】

第一行两个整数如上所述。

接下来行每行一个整数代表每个人所需要用的时间。

【输出格式】

一行一个整数表示答案。

【样例输入】

3 2

1

1

1

【样例输出】

1

【样例解释】

山里有座庙。

【数据规模与约定】

对于的数据,每个人所需用的时间不超过。

测试点

   

测试点

   

1

10

10

1

5000

500

2

20

10

2

100000

5000

3

50

10

3

100000

10000

4

1000

500

4

100000

20000

5

2000

500

5

100000

50000

 

_________________________________________________________________________________

这个题一看就是贪心,每一个人都找用时最少的,然后在加上去。维护时间可以用优先队列或是堆。堆太难写了,而优先队列有人反映很慢,于是就拿这个题练习了<algorithm>中的堆。

主要有四个函数

1、建堆make_heap(begin,end,cmp)

  将数组[begin,end)内的元素建堆,默认为大头堆,如需建小头堆加入greater<int>(),如果元素为结构体,则需重载运算符<.

2、加入堆push_heap(begin,end,cmp)

  将元素(end-1)加入堆,原本对的范围为[begin,end-1)

3、弹出堆pop_heap(begin,end,cmp)

  将堆顶(begin)与堆得最后一个元素(end-1)互换,从新调整堆。完成后堆的范围变成[begin,end-1)

4、堆排序sort_heap(begin,end,cmp)

  将堆得元素排序,默认为从小到大,加入greater<int>()后变为从大到小

_________________________________________________________________________________

 

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 int n,m;
 8 int sz[100010];
 9 void readint(int &x)
10 {
11     char c=getchar();
12     for(;c>'9'||c<'0';c=getchar());
13     x=0;
14     for(;c<='9'&&c>='0';c=getchar())x=x*10-'0'+c;
15 }
16 void print()
17 {
18     for(int i=0;i<n;i++)
19     cout<<sz[i]<<" ";
20     cout<<endl;
21 }
22 int main()
23 {
24     freopen("death.in","r",stdin);
25     freopen("death.out","w",stdout);
26     readint(n);readint(m);
27     for(int i=0;i<n;i++)
28     {
29         readint(sz[i]);
30     }
31     make_heap(sz,sz+m,greater<int>());
32     for(int i=m;i<n;i++)
33     {
34         pop_heap(sz,sz+m,greater<int>());
35         sz[m-1]+=sz[i];
36         push_heap(sz,sz+m,greater<int>());    
37     }
38     cout<<sz[0]<<endl;
39     fclose(stdin);
40     fclose(stdout);
41     return 0;
42 }

 

posted on 2016-11-08 15:36  gryzy  阅读(159)  评论(0编辑  收藏  举报

导航