-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_heap.cpp
More file actions
87 lines (84 loc) · 1.52 KB
/
Copy pathmax_heap.cpp
File metadata and controls
87 lines (84 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//max_heap or sorted in decreasing order
#include<cstdio>
#include<utility>
#include<iostream>
using namespace std;
#define s scanf
#define p printf
int arr[10000],ans[10000];
void insert_heap(int x)
{
while(arr[x]>arr[x/2])
{
swap(arr[x],arr[x/2]);
x/=2;
}
}
void build(int x)
{
int pos=1,y=2,z=3,mm;
if(z<=x)
{
mm=max(arr[y],arr[z]);
while(mm>arr[pos])
{
if(arr[z]<arr[y])
{
swap(arr[pos],arr[y]);
pos=y;
}
else
{
swap(arr[pos],arr[z]);
pos=z;
}
y=pos*2;
z=pos*2+1;
if(z<=x)
mm=max(arr[y],arr[z]);
else if(y==x)
{
if(arr[pos]<arr[y])
swap(arr[pos],arr[y]);
return ;
}
else
return ;
}
}
else if(x==y)
{
if(arr[pos]<arr[y])
swap(arr[pos],arr[y]);
}
else
return ;
}
int main()
{
int i,j,n;
arr[0]=2140000000;
while(s("%d",&n)==1)
{
for(i=1;i<=n;++i)
{
s("%d",&arr[i]);
insert_heap(i);
}
j=n;
for(i=1;i<=n;++i)
{
ans[i]=arr[1];
arr[1]=arr[j];
--j;
build(j);
}
p("Sorted List is: ");
for(i=1;i<=n;++i)
{
p(" %d",ans[i]);
}
p("\n\n");
}
return 0;
}