博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT L3-002: 堆栈(线段树)
阅读量:4655 次
发布时间:2019-06-09

本文共 1572 字,大约阅读时间需要 5 分钟。

题意:中文题意。

思路:因为所有数<=1e5,权值线段树维护每个数出现多少次,然后每次出栈入栈都更新权值就好了。

好久没写线段树了,写的好爽233。

1 #include 
2 using namespace std; 3 #define N 100010 4 #define lson rt<<1, l, m 5 #define rson rt<<1|1, m + 1, r 6 int tree[N<<2], val[N]; 7 stack
sta; 8 9 void pushup(int rt) { tree[rt] = tree[rt<<1] + tree[rt<<1|1]; }10 11 void update(int rt, int l, int r, int id, int val) {12 if(l == r && l == id) { tree[rt] += val; return ; }13 if(l == r) return ;14 int m = (l + r) >> 1;15 if(id <= m) update(lson, id, val);16 else update(rson, id, val);17 pushup(rt);18 }19 20 int query(int rt, int l, int r, int id) {21 if(l == r) return l;22 int m = (l + r) >> 1;23 if(tree[rt<<1] >= id) return query(lson, id);24 else return query(rson, id - tree[rt<<1]);25 }26 27 int main() {28 int n; scanf("%d", &n);29 char s[20]; int x, now; int ma = 100000;30 for(int i = 1; i <= n; i++) {31 scanf("%s", s);32 if(s[1] == 'o') {33 if(sta.empty()) { puts("Invalid"); continue; }34 now = sta.top(); sta.pop();35 update(1, 1, ma, now, -1);36 printf("%d\n", now);37 } else if(s[1] == 'e') {38 if(sta.empty()) { puts("Invalid"); continue; }39 now = query(1, 1, ma, (sta.size() + 1) / 2);40 printf("%d\n", now);41 } else {42 scanf("%d", &x);43 sta.push(x);44 update(1, 1, ma, x, 1);45 }46 }47 return 0;48 }

 

转载于:https://www.cnblogs.com/fightfordream/p/6614086.html

你可能感兴趣的文章
第二阶段站立会议7
查看>>
JAVA多线程
查看>>
delphi 更改DBGrid 颜色技巧
查看>>
POJ 2031 Building a Space Station
查看>>
面向对象1
查看>>
任意阶幻方(魔方矩阵)C语言实现
查看>>
织梦教程
查看>>
杭电多校 Harvest of Apples 莫队
查看>>
C/C++心得-结构体
查看>>
函数名作为参数传递
查看>>
apt-get for ubuntu 工具简介
查看>>
数值计算算法-多项式插值算法的实现与分析
查看>>
day8-异常处理与网络编程
查看>>
Python基础-time and datetime
查看>>
Linux epoll 笔记(高并发事件处理机制)
查看>>
shell脚本练习01
查看>>
WPF图标拾取器
查看>>
通过取父级for循环的i来理解闭包,iife,匿名函数
查看>>
HDU 3374 String Problem
查看>>
数据集
查看>>