PAT(A)1057 Stack (30point(s))(树状数组)

PAT(A)1057 Stack (30point(s))(树状数组)_第1张图片
PAT(A)1057 Stack (30point(s))(树状数组)_第2张图片
思路:
树状数组,每插入一个就对相应位置更新。
代码:

#include 

using namespace std;

typedef long long ll;
#define endl '\n'

stack<int>s;

const int maxn = 100010;

int c[maxn];

int lowbit(int x)
{
     
    return x & (-x);
}

void update(int x, int p)
{
     
    for (int i = x; i < maxn; i += lowbit(i))
        c[i] += p;
}

int getsum(int x)
{
     
    int s = 0;
    for (int i = x; i >= 1; i -= lowbit(i))
        s += c[i];

    return s;
}

void peek()
{
     
    int l = 1, r = maxn, mid, k = (s.size() + 1) / 2;

    while (l < r)
    {
     
        mid = (l + r) / 2;
        if (getsum(mid) >= k)
        {
     
            r = mid;
        }
        else
        {
     
            l = mid + 1;
        }
    }
    cout << l << endl;
}

int main()
{
     
    int n, temp;
    cin >> n;

    string ord;

    while (n--)
    {
     
        cin >> ord;
        if (ord[1] == 'u')
        {
     
            cin >> temp;
            s.push(temp);
            update(temp, 1);
        }
        else if (ord[1] == 'o')
        {
     
            if (!s.empty())
            {
     
                update(s.top(), -1);
                cout << s.top() << endl;
                s.pop();
            }
            else
                cout << "Invalid" << endl;
        }
        else if (ord[1] == 'e')
        {
     
            if (!s.empty())
                peek();
            else
                cout << "Invalid" << endl;
        }
    }

    return 0;
}

你可能感兴趣的:(PAT,(Advanced,Level),Practice)