快速排序法---题目(同堆排序法)

题目内容:

 

實作Max heap的三種操作:push, pop, top。

 

指令0 x:代表push,將x push進max heap。

指令1 : 代表pop,將最大的數字pop出來,若heap為空則忽略這道指令。

指令2 : 代表top,將最大的數字印出來,若heap為空則忽略這道指令。

 

输入格式:

 

本題只有一道測資。

測資第一行為一個數字N,代表接下來有N行指令。每行指令個格式如題目敘述。

 

所有push的數字皆不相同。

 

0 < N < 20000

0 < x < 10000000

 

输出格式:

 

將所有top指令輸出的數字作加總,最後輸出這個和。

Hint : 注意overflow!

 

 

输入样例:

 

15

1

0 9550684

0 8533293

1

2

2

1

0 505825

0 9809892

0 1484329

0 4958409

0 3788064

0 28006

2

0 2979864

 

 

输出样例:

 

26876478

 

时间限制:100ms内存限制:128000kb
 
 1 #include <stdio.h> 
 2 int cmd1,cmd2;
 3 int count = 0;
 4 long long sum = 0;
 5 long long a[20000];
 6 void quicksort(int left,int right) 
 7 { 
 8     int i,j,t,temp; 
 9     if(left>right) 
10        return; 
11                                 
12     temp=a[left]; 
13     i=left; 
14     j=right; 
15     while(i!=j) 
16     { 
17 
18                    while(a[j]<=temp && i<j) 
19                             j--; 
20 
21                    while(a[i]>=temp && i<j) 
22                             i++; 
23 
24                    if(i<j)
25                    { 
26                             t=a[i]; 
27                             a[i]=a[j]; 
28                             a[j]=t; 
29                    } 
30     } 
31 
32     a[left]=a[i]; 
33     a[i]=temp; 
34                              
35     quicksort(left,i-1);
36     quicksort(i+1,right);
37 } 
38 void push(long long a[]){
39     a[++count] = cmd2;
40     quicksort(1,count);
41 }
42 
43 void pop(long long a[]){
44     if(count==0){
45         return;
46     }
47     a[1] = a[count];
48     count--;
49     quicksort(a,count);
50     return;
51 }
52 
53 
54 void top(long long a[]){
55     sum +=a[1]; 
56 }
57 int main() 
58 { 
59     int n,i;
60     scanf("%d",&n);
61     for(i=0;i<n;i++){
62         scanf("%d",&cmd1);
63         if(cmd1==0){
64             scanf("%d",&cmd2);
65             push(a);
66         }
67 
68         if(cmd1==1){
69             pop(a);
70         }
71         if(cmd1==2){
72             top(a);
73         }
74     }
75     printf("%lld",sum);
76     return 0;
77 } 

 

posted @ 2016-02-29 21:32  江军1994  阅读(513)  评论(0)    收藏  举报