toj-3515-middle number(优先队列)

There is a sequence of integers, we have two operations now

1 add a: means add an integer a to the end of the sequence, forms a N+1 long sequence.

2 mid : Output the current sequence's middle numbera sequence's middle number is the middle position of the sequence when it's sorted by in creasing order.(if the sequence's length is even, then the middle position is the litter number's position of the two middle numbers)

example 1, sequence 1 2 13 14 15 16 and it's middle number is 13

example 2, sequence 1 3 5 7 10 11 17 and it's middle number is 7

example 3, 1 1 1 2 3 and it's middle number is 1

Input

The first line of the input gives the number of test cases T, for each test case the first line is the sequence's inital length N, the second line has N number represent the integer sequence. then third line is the operation number M then follows M lines, each line has the format either add a or mid (1<=N<=100000, 0<=M<=10000)

Output

each test case for each mid operation output the middle number

Sample Input

1
6
1 2 13 14 15 16
5
add 5
add 3
mid
add 20
mid

Sample Output

513

 

 

方法一:比较高级的高级队列,两个队列一小一大,保证每次操作后,输出的值都是big.top()

 

#include
#include
#include
using namespace std;

struct cmp1
{
    bool operator()(const int a, const int b) const
    {
        return a>b;
    }
};
struct cmp2
{
    bool operator()(const int a, const int b) const
    {
        return a     }
};
int main()
{
    int T, n, a[100005], m;
    priority_queue,cmp1>small;
    priority_queue,cmp2>big;
    cin >> T;
    while(T--)
    {
        while(!small.empty())
            small.pop();
        while(!big.empty())
            big.pop();
        cin >> n;
        for(int i=0; i             cin >> a[i];
        sort(a,a+n);
        int i, t;
        if(n&1)//n%2==1为奇
        {
            for(i=0; i                 big.push(a[i]);
        }
        else
        {
            for(i=0; i                 big.push(a[i]);
        }
        for(;i                 small.push(a[i]);
        cin >> m;
        string o;
        while(m--)
        {
           cin >> o;
           if(o[0] == 'a')
           {
               cin >> t;
               if(t < big.top())
               {
                   big.push(t);

               }
               else
               {
                   small.push(t);
               }
               if(big.size()>small.size()+1)
               {
                   int h = big.top();
                   small.push(h);
                   big.pop();
               }
               else if(big.size()                {
                   int k = small.top();
                   big.push(k);
                   small.pop();
               }
           }
           else
                cout << big.top() << endl;
        }
    }
    return 0;
}

 

 

你可能感兴趣的:(ACM刷题之路)