1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】
生活随笔
收集整理的這篇文章主要介紹了
1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
https://pintia.cn/problem-sets/994805342720868352/problems/994805417945710592
本題的一個(gè)最大的難點(diǎn),就是如何給一個(gè)動(dòng)態(tài)的區(qū)間內(nèi)快速的找到中間值。
可以很容易的想到用set,因?yàn)樗迦胧怯行虻摹5莝et是不可以存重復(fù)的值的,于是可以想到用multiset。
但是寫了一半,發(fā)現(xiàn)找中間迭代器不是太會(huì)。
于是看了一下柳神的做法,真的秒用樹狀數(shù)組+二分 碰巧的是昨天剛做了和這道題幾乎一模一樣做法的題。
于是快速的做了出來。
這里的數(shù)據(jù)范圍不會(huì)超過1e5 且都是正整數(shù) 所以可以用樹狀數(shù)組來維護(hù)前綴。
然后二分找中間值。
y總寫的multiset做法。其實(shí)本題見有的大佬用map來維護(hù)中間值也是很秀,但是感覺有點(diǎn)復(fù)雜。
#include <iostream> #include <cstring> #include <set> #include <stack>using namespace std;stack<int> stk; multiset<int> up, down;void adjust() {while (up.size() > down.size()){down.insert(*up.begin());up.erase(up.begin());}while (down.size() > up.size() + 1){auto it = down.end();it -- ;up.insert(*it);down.erase(it);} }int main() {int n;scanf("%d", &n);char op[20];while (n -- ){scanf("%s", op);if (strcmp(op, "Push") == 0){int x;scanf("%d", &x);stk.push(x);if (up.empty() || x < *up.begin()) down.insert(x);else up.insert(x);adjust();}else if (strcmp(op, "Pop") == 0){if (stk.empty()) puts("Invalid");else{int x = stk.top();stk.pop();printf("%d\n", x);auto it = down.end();it -- ;if (x <= *it) down.erase(down.find(x));else up.erase(up.find(x));adjust();}}else{if (stk.empty()) puts("Invalid");else{auto it = down.end();it -- ;printf("%d\n", *it);}}}return 0; }總結(jié)
以上是生活随笔為你收集整理的1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树状数组的基本板子
- 下一篇: 2021 RoboCom 世界机器人开发