创建最大堆,对指定位置元素进行删减
来源:互联网 发布:宿州云计算产业转移 编辑:程序博客网 时间:2024/05/02 00:53
在堆H上实现一种新的操作:DecreaseKey(H,P,X), 将堆H中,位于P的元素的值减去X。这个操作如何实现?当然,要求操作执行后,H仍然是个堆,堆中的元素允许移动。
#include <stdio.h>
#include <malloc.h>typedef struct maxhead1 *maxhead;
struct maxhead1
{
int *a; //to save the number
int size; //the current number of elements
int MAX; //the maximum number of elements
};
//Create a maximum tree
maxhead Create(int n)
{
maxhead H=malloc(sizeof(struct maxhead1));
H->a=malloc((n+1) * sizeof(struct maxhead1));
H->size=1;
H->MAX=n;
H->a[0]=10000;
return H;
}
void Insert(maxhead s,int n)
{
s->a[s->size]=n;
int child=s->size;
int parent;
for(;;child/=2)
{
parent=child/2;
if(s->a[child] < s->a[parent])
break;
else
{
s->a[child]=s->a[parent];
s->a[parent]=n;
}
}
}
//input the number
void input(maxhead s)
{
int k;
printf("please input the number:\n");
while(s->size <= s->MAX)
{
scanf("%d",&k);
Insert(s,k);
s->size++;
}
}
//change the node and create a new heap
void dcreaseKey(maxhead s,int p,int x)
{
int item=s->a[p]-x;
int parent;
int child;
for(parent = p;parent*2 <= s->size;parent=child)
{
child=parent*2;
if((child != s->size) &&
(s->a[child]<s->a[child+1]))
child++;
if(item >s->a[child])
break;
else
s->a[parent]=s->a[child];
}
s->a[parent]=item;
}
void printheap(maxhead s)
{
int i=1;
while( i <= (s->size-1) )
{
if( i != (s->size-1))
printf("%d ",s->a[i]);
else
printf("%d\n",s->a[i]);
i++;
}
}
int main()
{
setvbuf(stdout,NULL,_IONBF,0);
int n;
printf("please input how many data you want to have:\n");
scanf("%d",&n);
maxhead s=Create(n);
input(s);
printf("initial data:\n");
printheap(s);
int p,x;
printf("please input the site and the number you want to minus:\n");
scanf("%d %d",&p,&x);
dcreaseKey(s,p,x);
printf("processed data:\n");
printheap(s);
return 0;
}
0 0
- 创建最大堆,对指定位置元素进行删减
- 对数组进行指定位置的翻转
- 运用fstream对文本文件进行指定读取、删除,指定位置添加一行操作类
- 运用FILE对文本文件进行指定读取、删除,指定位置添加一行操作类
- 创建最大堆
- C++创建最大堆
- 创建最大堆
- 输出数组指定位置元素
- 第六章堆排序之“删除最大堆中的指定元素HEAP-DELETE”(练习6.5-7)
- 创建自己的结构元素对图象进行操作
- java list对元素进行指定多个字段属性按多种排序方式进行排序
- 对图片指定位置剪切
- 在一个List的指定位置插入一个元素对这个List中的已有的元素顺序的影响
- MySQL对表的修改(增加或删减列,创建或取消索引等)
- java去除字符串两端空格,对字符串指定位置进行反转。
- 创建最大(小)堆以及堆排序
- 使用指定的比较器对整个 System.Collections.ArrayList 中的元素进行排序。
- jQuery对指定元素中指定字符串进行替换的方法
- Codeforces Round #286 (Div. 2) C题 Mr. Kitayuta, the Treasure Hunter (DFS+记忆化DP)
- 微软发布Windows 10:连Windows 7都能免费升级了
- C# 反射技术应用
- JAVA学习笔记11——继承+重写
- MTK项目配置文件ProjectConfig.mk解析
- 创建最大堆,对指定位置元素进行删减
- common lisp教程
- (转载)linux命令之四十free 命令
- 淘宝内部分享:怎么跳出MySQL的10个大坑
- Appium grid ----appium 的并行化测试
- CLIST
- 多线程编程基础知识
- Hibernate中的cascade、inverse以及mappedBy用法 .
- Windows下下载安卓源码