题意是要你维护一个栈,元素是int,栈还有一个操作是查询栈中元素的中位数,也就是(cnt-1 )/2+1 == ceil(cnt,2);
第一次看见PAT有卡时间的题目(其他题就是暴力模拟、搜索、最短路), 暴力维护栈里的元素应该是不行的, 每次查询的复杂度是O(N);最坏情况应该是(N*N/4)
所以只能用好点的办法
这道题和19年湘潭ccpc一道题很像,
要求知道比一个数小的个数, 就是树状数组模板题。
然后要求找中位数, 就是在sum(1)~sum(n)上二分。
9月7日更新
网上看题解的时候发现了可以用带size的平衡树来写, stl的set是不带size 所以不能查询rank
而pb_ds的tree实现平衡树的时候加入了这些操作, 而用pair<int, int> 就可以实现存重复值
wdnmd 真的简单
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/assoc_container.hpp>
#include<iostream>
#include<unordered_map>
#include<stack>
using namespace std;
using namespace __gnu_pbds;
typedef pair<int, int> pii;
unordered_map<int, int> mp;
typedef tree<pii,null_type,less< pii >,rb_tree_tag,tree_order_statistics_node_update> RBT;
stack<int> stk;
RBT rbt;
int main()
{
//freopen("1157.in","r",stdin);
ios::sync_with_stdio(false);
int m;
cin>>m;
while(m--)
{
string s;
int op;
cin>>s;
if (s[1] == 'u')
{
cin>>op;
stk.push(op);
mp[op]+=1;
rbt.insert(pii(op,mp[op]));
}
else if (s[1] == 'o')
{
if (stk.empty())
{
cout<<"Invalid"<<endl;
continue;
}
int tp = stk.top();
stk.pop();
rbt.erase(pii(tp, mp[tp]));
mp[tp]-=1;
cout<<tp<<endl;
}
else
{
if (stk.empty())
{
cout<<"Invalid"<<endl;
continue;
}
cout<<(rbt.find_by_order((stk.size()-1)/2)->first)<<endl;
}
}
}
/*
维护一个栈, 和元素个数cnt
对于栈中可能出现的元素离散化到1~n;存放再A中
树状数组维护1~n对应的元素i sum(i) 表示 比 栈中<=A[i]的元素的个数,
由于sum(i)是单调递增的, 使用我们去二分 (cnt-1)/2+1 也就是median了
二分写法参考lower_bound.
*/
#include<bits/stdc++.h>
#define lb(x) (x&-x)
using namespace std;
const int N = 1e5+10;
typedef pair<string, int> P;
int A[N], C[N], n;
int stk[N], stk_top;
void add(int x, int v)
{
while(x<=n)
{
C[x]+=v;
x += lb(x);
}
}
int get_sum(int x)
{
int ret = 0;
while(x>=1)
{
ret+=C[x];
x -= lb(x);
}
return ret;
}
int get_p(int x)
{
return lower_bound(A+1,A+1+n,x) - A;
}
P op[N];
int op_top;
int main()
{
int m;
cin>>m;
string s;
int v;
while(m--)
{
v = 0;
cin>>s;
if (s[1] == 'u')
{
cin>>v;
A[++n] = v;
}
op[op_top++] = P(s,v);
}
/*cout<<"Input OK"<<endl;
for(int i=0;i<op_top;i++)
{
cout<<op[i].first<<" "<<op[i].second<<endl;
}*/
sort(A+1,A+1+n);
stk_top = -1;
for(int i=0;i<op_top;i++)
{
P &tp = op[i];
if (tp.first[1] == 'u')
{
add(get_p(tp.second), 1);
stk[++stk_top] = tp.second;
}
else if (tp.first[1] == 'o')
{
if (stk_top == -1)
{
cout<<"Invalid"<<endl;
continue;
}
int tv = stk[stk_top--];
add(get_p(tv), -1);
cout<<tv<<endl;
}
else
{
if (stk_top == -1)
{
cout<<"Invalid"<<endl;
continue;
}
int l = 1, r = n;
int target = stk_top/2+1;
while(l<r)
{
int m = 1ll*(l+r)/2;
if (get_sum(m)>=target)
{
r = m;
}
else
{
l = m+1;
}
}
cout<<A[l]<<endl;
}
}
return 0;
}