//本来是PTA上的一道题,但是超时而且输出没有和答案完全一样,作为记录保留至此
#include<stdio.h>
#include<iostream>
using namespace std;
#include<stdlib.h>
typedef int ElementType;
typedef struct Dui* hajimi;
int Wow = 20;//堆最大值
struct Dui {
ElementType* Data;
int size;//堆元素个数
int Maxd;
};
typedef hajimi ManBomax;//最大堆
typedef hajimi ManBomin;//最小堆
ManBomax CreateDui1(int maxsize)
{
ManBomax M = (ManBomax)malloc(sizeof(struct Dui));
M->Data = (ElementType*)malloc(sizeof(ElementType) * (maxsize + 1));
//留一位哨兵...
M->size = 0;
M->Maxd = maxsize;
M->Data[0] = 1145;
return M;
}
ManBomin CreateDui2(int maxsize)
{
ManBomin M = (ManBomin)malloc(sizeof(struct Dui));
M->Data = (ElementType*)malloc(sizeof(ElementType) * (maxsize + 1));
M->size = 0;
M->Maxd = maxsize;
M->Data[0] = -1;
return M;
}
bool Insert1(ManBomax M, ElementType e[],int count)//改成传数组而不是数,然后多一个参数count
{
int i = 0;
int j = 0;
while (j < count)
{
if (M->size==M->Maxd) return false;
i = ++M->size;
for (; M->Data[i / 2] < e[j]; i /= 2)
{
M->Data[i] = M->Data[i / 2];
//将e可能插入的位置上移,同时让上面让个位下来
}
M->Data[i] = e[j];
j++;
}
//printf("%d成功植入\n",M->Data[i]);
return true;
}
bool Insert2(ManBomin M, ElementType e[],int count)
{
int i = 0;
int j = 0;
while (j < count)
{
if (M->size==M->Maxd) return false;
i = ++M->size;
for (; M->Data[i / 2] > e[j]; i /= 2)
{
M->Data[i] = M->Data[i / 2];
//将e可能插入的位置上移,同时让上面让个位下来
}
M->Data[i] = e[j];
j++;
}
//printf("%d成功植入\n",M->Data[i]);
return true;
}
//ManBomin
int main()
{
ManBomax m1;
ManBomin m2;
int i = 0, count = 0;
scanf("%d", &count);
m1 = CreateDui1(count);
m2 = CreateDui2(count);
int* num = new int[count];
while (i < count)
{
cin >> num[i];
//printf("%d %d\n",i,count);
i++;
}
Insert1(m1, num, count);
Insert2(m2, num, count);
i=1;
while(i<count)
{
printf("%d ",m1->Data[i]);
i++;
}
printf("%d",m1->Data[i]);
printf("\n");
i=1;
while(i<count)
{
printf("%d ",m2->Data[i]);
i++;
}
printf("%d",m2->Data[i]);
//printf("%d %d",i,count);
return 0;
}

被折叠的 条评论
为什么被折叠?



