信息学奥赛一本通 第3章 第3节 堆及其应用(C++版)讲解.ppt

信息学奥赛一本通 第3章 第3节 堆及其应用(C++版)讲解.ppt

  1. 1、本文档共56页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
get和put操作的复杂度均为log2n。所以建堆复杂度为nlog2n。合并果子时,每次需要从堆中取出两个数,然后再加入一个数,因此一次合并的复杂度为3log2n,共n-1次。所以整道题目的复杂度是nlog2n。 【参考程序】 #include iostream #include cstdio using namespace std; int heap_size, n; int heap[30001]; void swap(int a, int b) //加后变量可修改 { int t = a;a = b;b = t; } void put(int d) { int now, next; heap[++heap_size] = d; now = heap_size; while(now 1) { next = now 1; if(heap[now] = heap[next])return; swap(heap[now], heap[next]); now = next; } } int get() { int now, next, res; res = heap[1]; heap[1] = heap[heap_size--]; now = 1; while(now * 2 = heap_size) { next = now * 2; if(next heap_size heap[next + 1] heap[next])next++; if(heap[now] = heap[next])return res; swap(heap[now], heap[next]); now = next; } return res; } void work() { int i, x, y, ans = 0; cin n; for(i = 1 ; i = n ; i++) //建堆,其实直接将数组排序也是建堆方法之一 { cin x; put(x); } for(i = 1 ; i n ; i++) //取、统计、插入 { x = get(); y = get(); //也可省去这一步,而直接将x累加到heap[1]然后调整 ans += x + y; put(x + y); } cout ans endl; } int main() { freopen(fruit.in, r, stdin); freopen(fruit.out, w, stdout); ios::sync_with_stdio(false); //优化。打消iostream的输入输出缓存,使得cin cout 时间和printf scanf 相差无几 work(); return 0; } 使用C++标准模板库STL: #include iostream #include queue #include cstdio using namespace std; int n; priority_queueint,vectorint,greaterint h; //优先队列 void work() { int i, x, y, ans = 0; cin n; for(i = 1 ; i = n ; i++) //建堆 { cin x; h.push(x); } for(i = 1 ; i n ; i++) //取、统计、插入 { x = h.top();h.pop(); y = h.top();h.pop(); ans += x + y; h.push(x + y); } cout ans endl; } int main() { freopen(fruit.in, r, stdin); freopen(fruit.out, w, stdout); work(); return 0; } 例2、堆排序(heapsort) 【问题描述】 假设n个数存放在A[1..n]中,我们可以利用堆将它们从小到大进行排序,这种排序方法,称为“堆排序”。输入两行,第1行为n,第2行为n个整数,每个数之间用1个空格隔开。输出1行,为从小到大排好序的n个数,每个数之间也用1个空格隔开。 【问题分析】 一种思路是完全按照上一个例题的方法去做。 【参考程序1】 #include iostream #i

文档评论(0)

shuwkb + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档