zoukankan      html  css  js  c++  java
  • 【堆】这是要搞事情啊——取出

    堆是什么?请点击


    取出

    取出加删除元素(小根堆)算法(简单粗略加通俗):

    1.取出根结点。

    2.最后一个节点将根结点覆盖,len--。

    3.循环:把根结点和它儿子中小的一个交换,直到没有儿子。

    硬模拟:

    int get()
    {
    	int now,next,res;
    	res=heap[0];
    	heap[0]=heap[--len];
    	now=0;
    	while(now*2<len)
    	{
    		next=now*2;
    		if(next<len&&heap[next+1]<heap[next])
    			next++;
    		if(heap[now]<=heap[next])
    			break;
    		swap(heap[now],heap[next]);
    		now=next;
    	}
    	return res;
    }
    以上代码编译过,未测试,呵呵,应该没问题。

    当然,直接库函数,懒癌福利(需添加algorithm、iostream及using namespace std头文件)

    int get()
    {
    	//pop_heap(heap,heap+len);//大根堆
    	pop_heap(heap,heap+len,greater<int>());//小根堆
    	return heap[--len];
    }


    至于堆吧,排序是可以的,其实很容易发现,建立堆过后每次get出来的就是最小(大根堆就是最大)的。

    以下是小根堆排序程序:

    //小根堆排序
    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int heap[100];
    int n,len;
    void put(int k)
    {
    	heap[len++]=k;
    	push_heap(heap,heap+len,greater<int>());
    }
    int get()
    {
    	pop_heap(heap,heap+len,greater<int>());
    	return heap[--len];
    }
    int main()
    {
    	int x;
    	scanf("%d",&n);
    	for(int i=0;i<n;i++)
    	{
    		scanf("%d",&x);
    		put(x);
    	}
    	for(int i=0;i<n;i++)
    		printf("%d ",get());
    	return 0;
    }
    

                                                                    By WZY


  • 相关阅读:
    修改linux的ssh默认端口号22的方法
    centos6 配置静态IP
    homebrew 无法安装提示不能在根目录下使用
    MySQL Replication 详解MySQL数据库设置主从同步的方法
    两台Mysql数据库数据同步实现
    MySql主从同步和延迟同步
    c#委托和事件
    C# Out和Ref区别
    MVC与三层架构
    经典数据库题
  • 原文地址:https://www.cnblogs.com/LinqiongTaoist/p/7203762.html
Copyright © 2011-2022 走看看