2 条题解
-
0
B3614 【模板】栈——题解
思路
用一个数组模拟栈,再用变量
top表示栈内元素个数:- 入栈:先让
top加一,再把新数放到a[top]; - 出栈:若
top>0,直接让top减一; - 查询:若
top>0,栈顶就是a[top]; - 大小:直接输出
top。
每组数据开始前把
top重新设为 。由于 可能接近 ,数组元素必须使用unsigned long long。复杂度
每条操作的时间复杂度为 ;数组最大占用 级别空间,本代码固定开到 。
参考代码
#include <bits/stdc++.h> using namespace std; const int N = 1000005; unsigned long long a[N]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int n, top = 0; cin >> n; while (n--) { string op; cin >> op; if (op == "push") { unsigned long long x; cin >> x; a[++top] = x; } else if (op == "pop") { if (top == 0) cout << "Empty\n"; else top--; } else if (op == "query") { if (top == 0) cout << "Anguei!\n"; else cout << a[top] << '\n'; } else { cout << top << '\n'; } } } return 0; } - 入栈:先让
-
0
#include <bits/stdc++.h> using namespace std; const int N = 1000005; unsigned long long a[N]; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin>>T; while(T--){ int n,top=0; cin>>n; while(n--){ string op; cin>>op; if(op=="push"){ unsigned long long x; cin>>x; a[++top]=x; }else if(op=="pop"){ if(top0) cout<<"Empty\n"; else top--; }else if(op"query"){ if(top==0) cout<<"Anguei!\n"; else cout<<a[top]<<'\n'; }else{ cout<<top<<'\n'; } } } return 0; }
- 1
信息
- ID
- 4942
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 10
- 标签
- 递交数
- 2
- 已通过
- 2
- 上传者
粤公网安备44195502000195号