-
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
时间限制:1 秒
内存限制:128 兆
题目描述:
-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(1<=n<=1000000), n代表将要输入的操作的步骤数。
接下来有n行,每行开始有一个字母Ci。
Ci=’s’时,接下有一个数字k,代表将k压入栈。
Ci=’o’时,弹出栈顶元素。
-
输出:
-
对应每个测试案例中的每个操作,
若栈不为空,输出相应的栈中最小元素。否则,输出NULL。
-
样例输入:
-
7 s 3 s 4 s 2 s 1 o o s 0
-
样例输出:
-
3 3 2 1 2 3 0
-
-
分析:使用两个栈来分别保存元素和最小值。
-
#include <iostream> #include <cstdio> using namespace std; const int N = 1000000; struct Stack { int array1[N]; int array2[N]; int top1; int top2; }; Stack st; int main(void) { int n, val; char str[2]; while (scanf("%d", &n) != EOF) { st.top1 = -1; st.top2 = -1; for (int i = 0; i < n; ++i) { scanf("%s", str); if (str[0] == 's') { scanf("%d", &val); st.array1[++st.top1] = val; if (st.top2 == -1 || st.array2[st.top2] >= val) st.array2[++st.top2] = val; printf("%d\n", st.array2[st.top2]); } else { if (st.top2 != -1) { if (st.array2[st.top2] == st.array1[st.top1]) st.top2--; st.top1--; if (st.top2 != -1) printf("%d\n", st.array2[st.top2]); else printf("NULL\n"); } else printf("NULL\n"); } } } return 0; }