创建最大堆,对指定位置元素进行删减

来源:互联网 发布:宿州云计算产业转移 编辑:程序博客网 时间: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
原创粉丝点击