Luo Gu P1168 median (PQ)

Topic Link

https://www.luogu.org/problemnew/show/P1168

Problem-solving ideas

This question is seeking median, but violence will tle, so we use the algorithm O (nlogn) to achieve.

This uses two stacks, a stack root is large, a small heap root, the root of the large number of small stack is always smaller than the number of root stack, and the difference between the number of a maximum of two stacks.

Figure (own hand painted, very beautiful, please forgive me):

It is like this, so that the two stacks top of the heap conspire easier to understand.

In this way, every answer is more number of elements in the stack top of the heap.

AC Code

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue> 
 4 using namespace std;
 5 const int maxn=100005;
 6 int n;
 7 priority_queue<int> q1;
 8 priority_queue<int,vector<int>,greater<int> > q2; 
 9 int main(){
10     cin>>n;
11     for(int i=1;i<=n;i++){
12         int a;
13         scanf("%d",&a);
14         int s1=q1.size();
15         int s2=q2.size();
16         if(s1==0) q1.push(a);
17         else{
18             int a1=q1.top();
19             if(a<=a1){
20                 q1.push(a);
21                 s1++;
22             }
23             else{
24                 q2.push(a);
25                 s2++;
26             }
27         }
28         while(s1-s2>1){
29             q2.push(q1.top());
30             q1.pop();
31             s1--;
32             s2++;
33         }
34         while(s2-s1>=1){
35             s2--;
36             s1++;
37             q1.push(q2.top());
38             q2.pop();
39         }
40         if(i%2==1) printf("%d\n",q1.top());
41     }
42     return 0;
43 }

 

Guess you like

Origin www.cnblogs.com/yinyuqin/p/11241174.html