1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】
生活随笔
收集整理的這篇文章主要介紹了
1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://pintia.cn/problem-sets/994805342720868352/problems/994805417945710592
本題的一個最大的難點,就是如何給一個動態的區間內快速的找到中間值。
可以很容易的想到用set,因為它插入是有序的。但是set是不可以存重復的值的,于是可以想到用multiset。
但是寫了一半,發現找中間迭代器不是太會。
于是看了一下柳神的做法,真的秒用樹狀數組+二分 碰巧的是昨天剛做了和這道題幾乎一模一樣做法的題。
于是快速的做了出來。
這里的數據范圍不會超過1e5 且都是正整數 所以可以用樹狀數組來維護前綴。
然后二分找中間值。
y總寫的multiset做法。其實本題見有的大佬用map來維護中間值也是很秀,但是感覺有點復雜。
#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; }總結
以上是生活随笔為你收集整理的1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树状数组的基本板子
- 下一篇: 2021 RoboCom 世界机器人开发