日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1057 Stack (30 分)【难度: 中 / 知识点: 树状数组 STL】

發(fā)布時(shí)間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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ù)前綴。
然后二分找中間值。

#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int tr[N],n; stack<int>st; int lowbit(int x){return x&(-x);} void add(int x,int c) {for(int i=x;i<N;i+=lowbit(i)) tr[i]+=c;} int sum(int x) {int res=0;for(int i=x;i;i-=lowbit(i)) res+=tr[i];return res; } int query()//二分找到答案 {int l=1,r=1e5;int len=st.size()/2;if(st.size()&1) len++;while(l<r){int mid=l+r>>1;if(sum(mid)>=len) r=mid;else l=mid+1;}return l; } int main(void) {cin>>n;while(n--){string op; cin>>op;if(op=="Pop"){if(st.size()){int temp=st.top(); st.pop();cout<<temp<<endl;add(temp,-1);}else puts("Invalid");}else if(op=="Push"){int x; cin>>x;st.push(x); add(x,1);}else{if(st.size()) cout<<query()<<endl;else puts("Invalid");}}return 0; }

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。