题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805417945710592
题目大意:模仿栈,只不过在原有的Push,Pop操作上,又加了一个PeekMedian操作,即当栈内的数是偶数时,输出第(n / 2)小的数,当栈内的数是奇数时,输出第(n + 1)/ 2小的数。
分析:树状数组+二分,或权值线段树(坤坤一语道破天机)。
树状数组+二分
#include <bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
const int N = 1e5 + 5;
int n, c[N];
char s[15];
stack<int> q;
int lowbit(int x) {
return x & (-x);
}
void update(int x, int w) {
while(x < N) {
c[x] += w;
x += lowbit(x);
}
}
int ask(int x) {
int sum = 0;
while(x) {
sum += c[x];
x -= lowbit(x);
}
return sum;
}
int find(int x) {
int l = 0, r = 1e5, ans;
while(l <= r) {
int mid = (l + r) >> 1;
if(ask(mid) < x) {
l = mid + 1;
} else {
r = mid - 1;
ans = mid;
}
}
return ans;
}
int main() {
scanf("%d", &n);
memset(c, 0, sizeof c);
while(n--) {
scanf("%s", s);
if(s[1] == 'u') {
int x;
scanf("%d", &x);
q.push(x);
update(x, 1);
} else if(s[1] == 'o') {
if(q.size() == 0) {
printf("Invalid\n");
} else {
int x = q.top();
q.pop();
printf("%d\n", x);
update(x, -1);
}
} else {
if(q.size() == 0) {
printf("Invalid\n");
} else {
int x = (q.size() + 1) / 2;
printf("%d\n", find(x));
}
}
}
return 0;
}
权值线段树
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n;
string s;
stack<int> q;
struct node {
int l, r, sum;
}tr[N<<2];
void pushup(int m) {
tr[m].sum = tr[m<<1].sum + tr[m<<1|1].sum;
}
void build(int m, int l, int r) {
tr[m].l = l;
tr[m].r = r;
tr[m].sum = 0;
if(l == r) return ;
int mid = (l + r) >> 1;
build(m<<1, l, mid);
build(m<<1|1, mid + 1, r);
}
void update(int m, int id, int w) {
if(tr[m].l == id && tr[m].r == id) {
tr[m].sum += w;
return ;
}
int mid = (tr[m].l + tr[m].r) >> 1;
if(id <= mid) update(m<<1, id, w);
else update(m<<1|1, id, w);
pushup(m);
}
int ask(int m, int num) {
if(tr[m].l == tr[m].r) return tr[m].l;
if(tr[m<<1].sum >= num) return ask(m<<1, num);
else return ask(m<<1|1, num - tr[m<<1].sum);
}
int main() {
build(1, 1, N);
scanf("%d", &n);
while(n--) {
cin >> s;
if(s == "Push") {
int x;
scanf("%d", &x);
q.push(x);
update(1, x, 1);
} else if(s == "Pop") {
if(q.size() == 0) printf("Invalid\n");
else {
int x = q.top();
q.pop();
printf("%d\n", x);
update(1, x, -1);
}
} else {
if(q.size() == 0) printf("Invalid\n");
else {
int x = q.size();
x = (x + 1) / 2;
printf("%d\n", ask(1, x));
}
}
}
return 0;
}