合并果子
来源:互联网 发布:网络视频教学平台 编辑:程序博客网 时间:2024/06/05 18:53
今天浅学了一下堆,发现这种东西简直就是为合并果子而生的啊!!!不仅风格上好看很多,而且很好理解啊!!而且c++模板库STL里面就只有堆的函数理解到了一点(蠢死了蠢死了
以下放原来用贪心的代码和用堆的进行对比:
#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<cstdlib>#include<algorithm>#include<ctime>#include<iomanip>#include<stack>#include<climits>#include<ctype.h>using namespace std;int b[30005],a[30005],n;int main(){ cin>>n; for(int i=1;i<=n;i++) scanf("%d",a+i); sort(a+1,a+n+1); int ans=0,t,m=0,i=1,j=1; for(int k=1;k<=n-1;k++){//贪心,其实每次都要反复理解,要不然很容易就忘了 if(m<j||i<=n&&a[i]<b[j]) t=a[i++]; else t=b[j++]; if(m<j||i<=n&&a[i]<b[j]) t+=a[i++]; else t+=b[j++]; ans+=t; b[++m]=t; } cout<<ans; return 0;}
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<algorithm>#include<ctime>#include<cctype>#include<vector>using namespace std;int heap_size,n;int heap[30001];void put(int d){ heap[++heap_size]=d; push_heap(heap+1,heap+heap_size+1,greater<int>());//STL}int get(){ pop_heap(heap+1,heap+heap_size+1,greater<int>()); return heap[heap_size--];}void work(){ int x,y,ans=0; cin>>n; for(int i=1;i<=n;i++){ cin>>x; put(x); } for(int i=1;i<n;i++){ x=get();//每次取两个小的合并 y=get(); ans+=x+y; put(x+y);//将合并后的插入小根堆 } cout<<ans<<endl;}int main(){ ios::sync_with_stdio(0);//读入优化 work(); return 0;}
继续努力。
阅读全文
1 0
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 果子合并
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 合并果子
- 大并发压测下,redis连接异常Read timed out排查优化
- 使用JAVA爬取网页图片
- [设计模式] 原型模式
- JUnit initializationError(org.junit.runner.manipulation.Filter)错误
- 编译原理--笔记
- 合并果子
- 单例模式
- MongoDB大中华区首席架构师唐建法:关系型数据库到MongoDB的战略迁移
- linux虚拟机安装
- struts1中表单提交乱码解决办法
- 1005: 整数幂
- Git暂存代码出现unable to auto detect email address '',Cannot save the current index state
- 加快控制台读取数据
- SpringMVC、Spring和Struts的区别