1076 排序 堆

1076 排序

 

时间限制: 1 s
空间限制: 128000 KB
题目等级 : 白银 Silver
 
 
 
 
题目描述 Description

给出n和n个整数,希望你从小到大给他们排序

输入描述 Input Description

第一行一个正整数n

 

 1 #include<iostream>
 2 #include<vector> 
 3 #include<algorithm>
 4 #include<cmath>
 5 using namespace std;
 6 int heap[1000000];
 7 int heap_size=0;
 8 int q;
 9 void put(int d)                 //heap[1]为堆顶
10 {
11     int now, next;
12     heap[++heap_size] = d;
13     now = heap_size;
14     while(now > 1)
15     {
16         next = now >> 1;
17         //next=now/(2,1);
18         if(heap[now] >= heap[next]) break;
19         swap(heap[now], heap[next]);
20         now = next;
21     }
22 }
23 /*void put(int d)
24 {
25     heap[++heap_size] = d;
26     //push_heap(heap + 1, heap + heap_size + 1);            //大根堆
27     push_heap(heap + 1, heap + heap_size + 1, greater<int>()); //小根堆
28 }*/
29 int get()                //heap[1]为堆顶
30 {
31     int now=1, next, res= heap[1];
32     heap[1] = heap[heap_size--];
33     while(now * 2 <= heap_size)
34     {
35         next = now * 2;
36         if (next < heap_size && heap[next + 1] < heap[next]) next++;
37         if (heap[now] <= heap[next]) break;
38         swap(heap[now], heap[next]);
39         now = next;
40     }
41     return res;
42 }
43 int main()
44 {
45     cin>>q;
46     for(int i=1;i<=q;i++)
47      {
48          cin>>heap[i];
49          put(heap[i]);
50      }
51     for(int j=1;j<=q;++j)
52     {
53         cout<<heap[1]<<" ";
54         get();
55     }
56     return 0;
57 }

 

第二行n个用空格隔开的整数

输出描述 Output Description

输出仅一行,从小到大输出n个用空格隔开的整数

样例输入 Sample Input

3

3 1 2

样例输出 Sample Output

1 2 3

数据范围及提示 Data Size & Hint

1<=n<=100000

posted @ 2017-03-31 15:30  ioioioioioio  阅读(124)  评论(0编辑  收藏  举报